Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question about Idiomatic Rust. #2

Closed
10thfloor opened this issue Sep 24, 2021 · 4 comments
Closed

Question about Idiomatic Rust. #2

10thfloor opened this issue Sep 24, 2021 · 4 comments

Comments

@10thfloor
Copy link

10thfloor commented Sep 24, 2021

Hello, as someone new to Rust, I have a query about borrowing and method calling syntax for a function that takes a string.

Should the calling syntax of SDK methods that take strings be simplified from, for example:

check_availability(&"grpc://access.devnet.nodes.onflow.org:9000".to_string()).await?;

to

check_availability(&"grpc://access.devnet.nodes.onflow.org:9000").await?;

If the function definition is modified as such (change the network_address parameter from &String to &str and use to_owned method instead of clone):

pub async fn check_availability(network_address: &str) -> Result<(), Box<dyn error::Error>> {
    let mut client = AccessApiClient::connect(network_address.to_owned()).await?;

    let request = tonic::Request::new(PingRequest {});

    client.ping(request).await?;

    Ok(())
}

Thought about posting on SO, but thought I would come here first, because it's easier to ask when there is some code for context.

@10thfloor
Copy link
Author

Haven't read too much Rust code in life, so apologies if this is redundant.

@MarshallBelles
Copy link
Owner

MarshallBelles commented Sep 24, 2021

@10thfloor

In Rust, when you specify a string as "hello world" what you are doing is creating a static non-mutable str (utf8 bytes) which has some limitations. The String class is heap-allocated to allow for mutability.

I chose to have a mutable String reference so that you only have to define your network_address once, and can make adjustments if needed. (This also makes the reference thread safe).

@10thfloor
Copy link
Author

Great. Thanks for the explanation.

@fee1-dead
Copy link

You could make adjustments with a String and convert that to &str relatively cheaply. &str is not limited to just literals.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants