How do I use from_str ? I have the snippet
let base: u32 = from_str::<u32>(&var)
and get the error
Error: unresolved name from_str
So I googled this error and found this, so I tried adding the following
use std::u32;
use std::from_str::FromStr
But now I get
Error: unresolved import `std::from_str::FromStr` could not from `from_str` in `std`
According to this github issue, I need to include this yet rust can't find it. What's going on? Here's a super simple program which gives me those errors
use std::u32;
use std::from_str::FromStr;
fn main() {
let my_str = "String".to_string();
let base: u32 = from_str(&my_str);
}
This is such a trivial issue and yet these resources are only showing me how to get more errors.
Use the docs to search for from_str. They show that the FromStr trait is in std::str now, not std::from_str. (April 2014 is a long time ago in Rust terms, being well before Rust 1.0.0.)
FromStr should not be used directly in general anyway; you should use str.parse method instead: my_str.parse::<u32>(). Remember that it returns a Result, because the string might just not contain a number.
Related
Recently, I started to learn rust. I'm currently at section 7.4 (bringing paths into scope). Tried hard, but I can't understand the purpose of self::some_sort_of_identifier in rust. Would you please explain what is the difference between use self::module_name::function_name and use module_name::function_name? I tried both and they both worked as expected in the example below:
mod my_mod {
pub fn func() {
print!("I'm here!");
}
}
use my_mod::func;
fn main() {
func();
}
Running this program, as expected, I can see this statement printed into the terminal:
I'm here
And this program here gives me exactly the same results and the rust compiler doesn't complain about anything:
mod my_mod {
pub fn func() {
print!("I'm here!");
}
}
use self::my_mod::func;
fn main() {
func();
}
So, is self:: useless in rust? Why should I even use self::my_mod::my_function(); when I can directly call it like so: my_mod::my_function();.
Are there any cases in which they might defer?
For your use-case, it's mainly a relict from the 2015 rust edition.
In this edition the following code would not compile:
use my_mod::func;
mod my_mod {
use my_mod2::func2;
pub fn func() {
func2();
}
mod my_mod2 {
pub fn func2() {
print!("I'm here!");
}
}
}
fn main() {
func();
}
The compiler complains:
error[E0432]: unresolved import my_mod2
--> src\main.rs:4:9
|
| use my_mod2::func2;
| ^^^^^^^ help: a similar path exists: self::my_mod2
Why did it change? You can see the note about the path and module system changes here.
Rust 2018 simplifies and unifies path handling compared to Rust 2015. In Rust
2015, paths work differently in use declarations than they do
elsewhere. In particular, paths in use declarations would always start
from the crate root, while paths in other code implicitly started from
the current scope. Those differences didn't have any effect in the
top-level module, which meant that everything would seem
straightforward until working on a project large enough to have
submodules.
In Rust 2018, paths in use declarations and in other code work the
same way, both in the top-level module and in any submodule. You can
use a relative path from the current scope, a path starting from an
external crate name, or a path starting with crate, super, or self.
The blog post Anchored and Uniform Paths from the language team also underlines this
The uniformity is a really big advantage, and the specific feature we’re changing -
no longer having to use self:: - is something I know is a big
stumbling block for new users and a big annoyance for advanced users
(I’m always having to edit and recompile because I tried to import
from a submodule without using self).
The keyword itself however is still useful in use statments to refer to the current module in the path itself. Like
use std::io::{self, Read};
being the same as
use std::io;
use std::io::Read;
I have read this article here and I understood that HashMap is not usable in Solana, thus, I need to use BTreeMap.
I am a beginner in Rust and I am having an error with the following code when trying to move from Ethereum to Solana :
pub fn constructor (
let mut DomainsToIndex = BTreeMap::new();
Domains[] pub DomainList;
contractOwner = msg.sender;
firstDomain.name = "empty";
firstDomain.IP = "n/a";
firstDomain.owner = 0;
firstDomain.lockTime = 0;
firstDomain.infoDocumentHash = "n/a";
DomainsToIndex.insert(String::from(firstDomain.name), 0);
DomainList.push(firstDomain);
) -> ProgramResult {
msg!("First domain was added by default");
Ok(())
}
I of course added the import in the top of the file with:
use std::collections::BTreeMap;
The error I receive when using cargo build is the following as per the image presented below:
I presume that I am not doing something right, as I am a newbie in Rust, can you please help out ?
Thanks.
There are a couple of syntactical issues with the code.
Application arguments should be separate from the body and pub without a struct doesn't make sense either.
Unfortunately the documentation of their Rust interface is quite lacking (seems to be mostly "have a look at some examples then find out the rest through trial-and-error"). So I was unable to look up enough information to suggest a reasonably correct version.
Here are a couple of more pointers:
it's not clear what the input to this function is. You're referencing a msg object with a sender member there, but the only equivalent I could identify was the &[AccountInfo] argument which identifies the invoking account.
Alternatively, Solana programs receive a byte array of instruction data which apparently can have any content encoded within them.
I would suggest starting with their Hello World example, playing around with it a bit and continue with your own app once you're more familiar with Rust syntax and Solana best practices.
I have the following code block and it works as intended with no problem:
fn literal_taker(literals_slice: &[&str]){
println!("{:?}",literals_slice);
}
fn string_taker(string_value: String){
literal_taker(&[&string_value]);
}
fn main() {
let string_value = String::from("Hello");
string_taker(string_value);
}
Here, I pass the reference of String as a slice and it is compiling with no error and no clippy issue.
But the problem is, It is shown as warning in Clion Rust plugin:
Is it a bug of an plugin or am I doing something bad practice in Rust?
Playground
CLion Rust Plugin Version: 0.2.0.2106-182
The code does compile as written, as the playground clearly demonstrates. Therefore it is a bug in the IDEA Rust Plugin.
Unlike most other Rust plugins that use the Rust Language Server, which uses code from the compiler, and therefore generally provides diagnostics consistent with what the compiler will, IntelliJ IDEA has its own validator, which might get things wrong.
I am using raw-cpuid crate for a project. It uses raw::Slice structure in processor_brand_string() function of ExtendedFunctionInfo structure.
let slice = raw::Slice { data: brand_string_start, len: 3*4*4 };
The above statement doesn't compile. It aborts with this error
cannot find struct, variant or union type `Slice` in module `raw`
--> /home/ubuntu/.cargo/registry/src/github.com-1ecc6299db9ec823/raw-cpuid-2.0.0/src/lib.rs:435:25
|
435 | let slice = raw::Slice { data: brand_string_start, len: 3*4 };
| ^^^^^^^^^^ not found in `raw`
The crate uses no_std attribute. The Rust book says
When we’re using the standard library, Rust automatically brings std
into scope, allowing you to use its features without an explicit
import. By the same token, when using #![no_std], Rust will bring core
into scope for you, as well as its prelude. This means that a lot of
code will Just Work.
I checked the core crate and it has Slice structure in the raw module. I have searched for any resolution of this error but I couldn't find one and me being new to Rust am unable to figure out what to do. I don't think many have used this crate but any help is appreciated. Thanks
I have been watching Rust for the past few months but I just started into an actual project. I am not sure if the terminology in the title is correct. Please let me know how it can be corrected.
I am writing a rust wrapper around the ENet library (http://enet.bespin.org). My goal is to keep the rust API as similar to the C API as possible except to refactor functions that take C style handle pointers into member functions of structure objects. I want to keep the API similar so that the official C documentation will apply equally well to the rust wrapper.
ENet exposes a single function to create either a client host or a server host. When creating a server you pass a pointer to an IP Address structure to the function. When creating a client you pass NULL.
I am trying to emulate that behavior using the ToSocketAddr trait and Option but I am running into problems using them in conjunction.
This is a reduced example of what I am trying to do:
use std::io::net::ip::ToSocketAddr;
fn create_host<A: ToSocketAddr>(addr: Option<A>) {
match addr {
Some(a) => println!("Address is {}. Return a server host object.",a.to_socket_addr()),
None => println!("no address... Return a client.")
};
}
fn main() {
create_host(Some("localhost:12345"));
create_host(None);
}
The first call to create_host() works like a charm. The second call however will not compile.
Rustc returns
error: unable to infer enough type information about `_`; type annotations required
I am guessing that error is occurring because None doesn't provide any resolution to the generic A. I tried the following but this doesn't work either because ToSocketAddr does not implement the trait core::kinds::Sized.
fn create_host(addr: Option<ToSocketAddr>) {
...
}
Is there a way I can do this or do I need to take a different approach?
fn main() {
create_host(Some("localhost:12345"));
create_host(None::<&str>);
}
I've chosen &str here as it is the same type as on the first call, so that the compiler wouldn't generate another monomorphized version of the generic function. You could choose any type that implements ToSocketAddr.