Trait sp_std::str::FromStr

1.0.0 · source · []
pub trait FromStr {
    type Err;
    fn from_str(s: &str) -> Result<Self, Self::Err>;
}
Expand description

Parse a value from a string

FromStr’s from_str method is often used implicitly, through str’s parse method. See parse’s documentation for examples.

FromStr does not have a lifetime parameter, and so you can only parse types that do not contain a lifetime parameter themselves. In other words, you can parse an i32 with FromStr, but not a &i32. You can parse a struct that contains an i32, but not one that contains an &i32.

Examples

Basic implementation of FromStr on an example Point type:

use std::str::FromStr;
use std::num::ParseIntError;

#[derive(Debug, PartialEq)]
struct Point {
    x: i32,
    y: i32
}

impl FromStr for Point {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
                                 .split(',')
                                 .collect();

        let x_fromstr = coords[0].parse::<i32>()?;
        let y_fromstr = coords[1].parse::<i32>()?;

        Ok(Point { x: x_fromstr, y: y_fromstr })
    }
}

let p = Point::from_str("(1,2)");
assert_eq!(p.unwrap(), Point{ x: 1, y: 2} )

Associated Types

The associated error which can be returned from parsing.

Required methods

Parses a string s to return a value of this type.

If parsing succeeds, return the value inside Ok, otherwise when the string is ill-formatted return an error specific to the inside Err. The error type is specific to the implementation of the trait.

Examples

Basic usage with i32, a type that implements FromStr:

use std::str::FromStr;

let s = "5";
let x = i32::from_str(s).unwrap();

assert_eq!(5, x);

Implementations on Foreign Types

Parse a bool from a string.

Yields a Result<bool, ParseBoolError>, because s may or may not actually be parseable.

Examples
use std::str::FromStr;

assert_eq!(FromStr::from_str("true"), Ok(true));
assert_eq!(FromStr::from_str("false"), Ok(false));
assert!(<bool as FromStr>::from_str("not even a boolean").is_err());

Note, in many cases, the .parse() method on str is more proper.

assert_eq!("true".parse(), Ok(true));
assert_eq!("false".parse(), Ok(false));
assert!("not even a boolean".parse::<bool>().is_err());

Converts a string in base 10 to a float. Accepts an optional decimal exponent.

This function accepts strings such as

  • ‘3.14’
  • ‘-3.14’
  • ‘2.5E10’, or equivalently, ‘2.5e10’
  • ‘2.5E-10’
  • ‘5.’
  • ‘.5’, or, equivalently, ‘0.5’
  • ‘inf’, ‘-inf’, ‘NaN’

Leading and trailing whitespace represent an error.

Grammar

All strings that adhere to the following EBNF grammar will result in an Ok being returned:

Float  ::= Sign? ( 'inf' | 'NaN' | Number )
Number ::= ( Digit+ |
             Digit+ '.' Digit* |
             Digit* '.' Digit+ ) Exp?
Exp    ::= [eE] Sign? Digit+
Sign   ::= [+-]
Digit  ::= [0-9]
Arguments
  • src - A string
Return value

Err(ParseFloatError) if the string did not represent a valid number. Otherwise, Ok(n) where n is the floating-point number represented by src.

Converts a string in base 10 to a float. Accepts an optional decimal exponent.

This function accepts strings such as

  • ‘3.14’
  • ‘-3.14’
  • ‘2.5E10’, or equivalently, ‘2.5e10’
  • ‘2.5E-10’
  • ‘5.’
  • ‘.5’, or, equivalently, ‘0.5’
  • ‘inf’, ‘-inf’, ‘NaN’

Leading and trailing whitespace represent an error.

Grammar

All strings that adhere to the following EBNF grammar will result in an Ok being returned:

Float  ::= Sign? ( 'inf' | 'NaN' | Number )
Number ::= ( Digit+ |
             Digit+ '.' Digit* |
             Digit* '.' Digit+ ) Exp?
Exp    ::= [eE] Sign? Digit+
Sign   ::= [+-]
Digit  ::= [0-9]
Arguments
  • src - A string
Return value

Err(ParseFloatError) if the string did not represent a valid number. Otherwise, Ok(n) where n is the floating-point number represented by src.

Implementors

impl<const CAP: usize> FromStr for ArrayString<CAP>

impl FromStr for PathBuf

impl FromStr for DateTime<Utc>

impl FromStr for Weekday

impl FromStr for Month

impl<const S: usize> FromStr for Cid<S>

impl FromStr for Shell

impl FromStr for Imm64

impl FromStr for Uimm64

impl FromStr for Uimm32

impl FromStr for Offset32

impl FromStr for Ieee32

impl FromStr for Ieee64

impl FromStr for Opcode

impl FromStr for LibCall

impl FromStr for TrapCode

impl FromStr for CallConv

impl FromStr for Regalloc

impl FromStr for OptLevel

impl FromStr for TlsModel

impl FromStr for IntCC

impl FromStr for FloatCC

impl FromStr for Glob

impl FromStr for Method

impl FromStr for Scheme

impl FromStr for Uri

impl FromStr for HttpDate

impl FromStr for Duration

impl FromStr for Name

impl FromStr for IpNet

impl FromStr for Ipv4Net

impl FromStr for Ipv6Net

impl FromStr for JsString

impl FromStr for PeerId

impl FromStr for Level

impl FromStr for Pattern

impl FromStr for BigInt

impl FromStr for BigUint

impl<T> FromStr for Complex<T> where
    T: FromStr + Num + Clone

impl<T: FromStr + Clone + Integer> FromStr for Ratio<T>

impl FromStr for U128

impl FromStr for U256

impl FromStr for U512

impl FromStr for H128

impl FromStr for H160

impl FromStr for H256

impl FromStr for H512

impl FromStr for Literal

impl FromStr for Regex

impl FromStr for Regex

impl FromStr for Database

impl FromStr for Number

impl FromStr for Value

impl FromStr for DHChoice

impl FromStr for FixedI64

impl FromStr for Public

impl FromStr for Public

impl FromStr for Bytes

impl FromStr for Keyring

impl FromStr for Vendor

impl FromStr for Triple

impl FromStr for Color

impl FromStr for Value

impl FromStr for Datetime

impl FromStr for Level

impl<S: FromStr> FromStr for Ascii<S>

impl<S: FromStr + AsRef<str>> FromStr for UniCase<S>

impl FromStr for Url