Trait FromStr

1.6.0 (const: unstable) ยท Source
pub trait FromStr: Sized {
    type Err;

    // Required method
    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.

ยงInput format and round-tripping

The input format expected by a typeโ€™s FromStr implementation depends on the type. Check the typeโ€™s documentation for the input formats it knows how to parse. Note that the input format of a typeโ€™s FromStr implementation might not necessarily accept the output format of its Display implementation, and even if it does, the Display implementation may not be lossless so the round-trip may lose information.

However, if a type has a lossless Display implementation whose output is meant to be conveniently machine-parseable and not just meant for human consumption, then the type may wish to accept the same format in FromStr, and document that usage. Having both Display and FromStr implementations where the result of Display cannot be parsed with FromStr may surprise users.

ยงExamples

Basic implementation of FromStr on an example Point type:

use std::str::FromStr;

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

#[derive(Debug, PartialEq, Eq)]
struct ParsePointError;

impl FromStr for Point {
    type Err = ParsePointError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (x, y) = s
            .strip_prefix('(')
            .and_then(|s| s.strip_suffix(')'))
            .and_then(|s| s.split_once(','))
            .ok_or(ParsePointError)?;

        let x_fromstr = x.parse::<i32>().map_err(|_| ParsePointError)?;
        let y_fromstr = y.parse::<i32>().map_err(|_| ParsePointError)?;

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

let expected = Ok(Point { x: 1, y: 2 });
// Explicit call
assert_eq!(Point::from_str("(1,2)"), expected);
// Implicit calls, through parse
assert_eq!("(1,2)".parse(), expected);
assert_eq!("(1,2)".parse::<Point>(), expected);
// Invalid input string
assert!(Point::from_str("(1 2)").is_err());

Required Associated Typesยง

1.0.0 ยท Source

type Err

The associated error which can be returned from parsing.

Required Methodsยง

1.0.0 ยท Source

fn from_str(s: &str) -> Result<Self, Self::Err>

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);

Dyn Compatibilityยง

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementorsยง

Sourceยง

impl FromStr for LoginError

Sourceยง

type Err = ParseError

Sourceยง

impl FromStr for AssocType

Sourceยง

impl FromStr for ArgMode

Sourceยง

impl FromStr for flams_ontology::languages::Language

Sourceยง

impl FromStr for ParagraphKind

Sourceยง

impl FromStr for AnswerKind

Sourceยง

impl FromStr for CognitiveDimension

Sourceยง

impl FromStr for ContentURI

Sourceยง

impl FromStr for URI

Sourceยง

impl FromStr for NarrativeURI

Sourceยง

impl FromStr for TermURI

Sourceยง

impl FromStr for LogLevel

ยง

impl FromStr for Env

ยง

type Err = ()

ยง

impl FromStr for ReloadWSProtocol

ยง

type Err = ()

1.7.0 ยท Sourceยง

impl FromStr for IpAddr

1.0.0 ยท Sourceยง

impl FromStr for SocketAddr

Sourceยง

impl FromStr for chrono::month::Month

Parsing a str into a Month uses the format %B.

ยงExample

use chrono::Month;

assert_eq!("January".parse::<Month>(), Ok(Month::January));
assert!("any day".parse::<Month>().is_err());

The parsing is case-insensitive.

assert_eq!("fEbruARy".parse::<Month>(), Ok(Month::February));

Only the shortest form (e.g. jan) and the longest form (e.g. january) is accepted.

assert!("septem".parse::<Month>().is_err());
assert!("Augustin".parse::<Month>().is_err());
Sourceยง

impl FromStr for chrono::weekday::Weekday

Parsing a str into a Weekday uses the format %A.

ยงExample

use chrono::Weekday;

assert_eq!("Sunday".parse::<Weekday>(), Ok(Weekday::Sun));
assert!("any day".parse::<Weekday>().is_err());

The parsing is case-insensitive.

assert_eq!("mON".parse::<Weekday>(), Ok(Weekday::Mon));

Only the shortest form (e.g. sun) and the longest form (e.g. sunday) is accepted.

assert!("thurs".parse::<Weekday>().is_err());
Sourceยง

impl FromStr for IpNet

Sourceยง

impl FromStr for log::Level

Sourceยง

impl FromStr for log::LevelFilter

Sourceยง

impl FromStr for serde_json::value::Value

1.0.0 ยท Sourceยง

impl FromStr for bool

1.20.0 ยท Sourceยง

impl FromStr for char

1.0.0 ยท Sourceยง

impl FromStr for f16

1.0.0 ยท Sourceยง

impl FromStr for f32

1.0.0 ยท Sourceยง

impl FromStr for f64

1.0.0 (const: unstable) ยท Sourceยง

impl FromStr for i8

1.0.0 (const: unstable) ยท Sourceยง

impl FromStr for i16

1.0.0 (const: unstable) ยท Sourceยง

impl FromStr for i32

1.0.0 (const: unstable) ยท Sourceยง

impl FromStr for i64

1.0.0 (const: unstable) ยท Sourceยง

impl FromStr for i128

1.0.0 (const: unstable) ยท Sourceยง

impl FromStr for isize

1.0.0 (const: unstable) ยท Sourceยง

impl FromStr for u8

1.0.0 (const: unstable) ยท Sourceยง

impl FromStr for u16

1.0.0 (const: unstable) ยท Sourceยง

impl FromStr for u32

1.0.0 (const: unstable) ยท Sourceยง

impl FromStr for u64

1.0.0 (const: unstable) ยท Sourceยง

impl FromStr for u128

1.0.0 (const: unstable) ยท Sourceยง

impl FromStr for usize

Sourceยง

impl FromStr for ArgSpec

Sourceยง

impl FromStr for DocumentStyle

Sourceยง

impl FromStr for ArchiveId

Sourceยง

impl FromStr for ArchiveURI

Sourceยง

impl FromStr for BaseURI

Sourceยง

impl FromStr for ModuleURI

Sourceยง

impl FromStr for SymbolURI

Sourceยง

impl FromStr for flams_ontology::uris::name::Name

Sourceยง

impl FromStr for DocumentElementURI

Sourceยง

impl FromStr for DocumentURI

Sourceยง

impl FromStr for PathURI

Sourceยง

impl FromStr for Timestamp

ยง

impl FromStr for HeaderName

ยง

impl FromStr for HeaderValue

ยง

impl FromStr for Method

ยง

impl FromStr for StatusCode

ยง

impl FromStr for Uri

ยง

impl FromStr for Authority

ยง

impl FromStr for PathAndQuery

ยง

impl FromStr for flams_router_vscode::server_fn::axum_export::http::uri::Scheme

ยง

impl FromStr for NoCustomError

ยง

type Err = ()

1.0.0 ยท Sourceยง

impl FromStr for Ipv4Addr

1.0.0 ยท Sourceยง

impl FromStr for Ipv6Addr

1.5.0 ยท Sourceยง

impl FromStr for SocketAddrV4

1.5.0 ยท Sourceยง

impl FromStr for SocketAddrV6

1.35.0 ยท Sourceยง

impl FromStr for NonZero<i8>

1.35.0 ยท Sourceยง

impl FromStr for NonZero<i16>

1.35.0 ยท Sourceยง

impl FromStr for NonZero<i32>

1.35.0 ยท Sourceยง

impl FromStr for NonZero<i64>

1.35.0 ยท Sourceยง

impl FromStr for NonZero<i128>

1.35.0 ยท Sourceยง

impl FromStr for NonZero<isize>

1.35.0 ยท Sourceยง

impl FromStr for NonZero<u8>

1.35.0 ยท Sourceยง

impl FromStr for NonZero<u16>

1.35.0 ยท Sourceยง

impl FromStr for NonZero<u32>

1.35.0 ยท Sourceยง

impl FromStr for NonZero<u64>

1.35.0 ยท Sourceยง

impl FromStr for NonZero<u128>

1.35.0 ยท Sourceยง

impl FromStr for NonZero<usize>

Sourceยง

impl FromStr for ByteString

1.85.0 ยท Sourceยง

impl FromStr for CString

1.0.0 ยท Sourceยง

impl FromStr for String

1.54.0 ยท Sourceยง

impl FromStr for proc_macro::Literal

Parse a single literal from its stringified representation.

In order to parse successfully, the input string must not contain anything but the literal token. Specifically, it must not contain whitespace or comments in addition to the literal.

The resulting literal token will have a Span::call_site() span.

NOTE: some errors may cause panics instead of returning LexError. We reserve the right to change these errors into LexErrors later.

1.15.0 ยท Sourceยง

impl FromStr for proc_macro::TokenStream

Attempts to break the string into tokens and parse those tokens into a token stream. May fail for a number of reasons, for example, if the string contains unbalanced delimiters or characters not existing in the language. All tokens in the parsed stream get Span::call_site() spans.

NOTE: some errors may cause panics instead of returning LexError. We reserve the right to change these errors into LexErrors later.

1.45.0 ยท Sourceยง

impl FromStr for OsString

1.32.0 ยท Sourceยง

impl FromStr for PathBuf

Sourceยง

impl FromStr for chrono::datetime::DateTime<FixedOffset>

Accepts a relaxed form of RFC3339. A space or a โ€˜Tโ€™ are accepted as the separator between the date and time parts. Additional spaces are allowed between each component.

All of these examples are equivalent:

"2012-12-12T12:12:12Z".parse::<DateTime<FixedOffset>>()?;
"2012-12-12 12:12:12Z".parse::<DateTime<FixedOffset>>()?;
"2012-  12-12T12:  12:12Z".parse::<DateTime<FixedOffset>>()?;
Sourceยง

impl FromStr for chrono::datetime::DateTime<Local>

Accepts a relaxed form of RFC3339. A space or a โ€˜Tโ€™ are accepted as the separator between the date and time parts.

All of these examples are equivalent:

"2012-12-12T12:12:12Z".parse::<DateTime<Local>>()?;
"2012-12-12 12:12:12Z".parse::<DateTime<Local>>()?;
"2012-12-12 12:12:12+0000".parse::<DateTime<Local>>()?;
"2012-12-12 12:12:12+00:00".parse::<DateTime<Local>>()?;
Sourceยง

impl FromStr for chrono::datetime::DateTime<Utc>

Accepts a relaxed form of RFC3339. A space or a โ€˜Tโ€™ are accepted as the separator between the date and time parts.

All of these examples are equivalent:

"2012-12-12T12:12:12Z".parse::<DateTime<Utc>>()?;
"2012-12-12 12:12:12Z".parse::<DateTime<Utc>>()?;
"2012-12-12 12:12:12+0000".parse::<DateTime<Utc>>()?;
"2012-12-12 12:12:12+00:00".parse::<DateTime<Utc>>()?;
Sourceยง

impl FromStr for NaiveDate

Parsing a str into a NaiveDate uses the same format, %Y-%m-%d, as in Debug and Display.

ยงExample

use chrono::NaiveDate;

let d = NaiveDate::from_ymd_opt(2015, 9, 18).unwrap();
assert_eq!("2015-09-18".parse::<NaiveDate>(), Ok(d));

let d = NaiveDate::from_ymd_opt(12345, 6, 7).unwrap();
assert_eq!("+12345-6-7".parse::<NaiveDate>(), Ok(d));

assert!("foo".parse::<NaiveDate>().is_err());
Sourceยง

impl FromStr for NaiveDateTime

Parsing a str into a NaiveDateTime uses the same format, %Y-%m-%dT%H:%M:%S%.f, as in Debug.

ยงExample

use chrono::{NaiveDateTime, NaiveDate};

let dt = NaiveDate::from_ymd_opt(2015, 9, 18).unwrap().and_hms_opt(23, 56, 4).unwrap();
assert_eq!("2015-09-18T23:56:04".parse::<NaiveDateTime>(), Ok(dt));

let dt = NaiveDate::from_ymd_opt(12345, 6, 7).unwrap().and_hms_milli_opt(7, 59, 59, 1_500).unwrap(); // leap second
assert_eq!("+12345-6-7T7:59:60.5".parse::<NaiveDateTime>(), Ok(dt));

assert!("foo".parse::<NaiveDateTime>().is_err());
Sourceยง

impl FromStr for NaiveTime

Parsing a str into a NaiveTime uses the same format, %H:%M:%S%.f, as in Debug and Display.

ยงExample

use chrono::NaiveTime;

let t = NaiveTime::from_hms_opt(23, 56, 4).unwrap();
assert_eq!("23:56:04".parse::<NaiveTime>(), Ok(t));

let t = NaiveTime::from_hms_nano_opt(23, 56, 4, 12_345_678).unwrap();
assert_eq!("23:56:4.012345678".parse::<NaiveTime>(), Ok(t));

let t = NaiveTime::from_hms_nano_opt(23, 59, 59, 1_234_567_890).unwrap(); // leap second
assert_eq!("23:59:60.23456789".parse::<NaiveTime>(), Ok(t));

// Seconds are optional
let t = NaiveTime::from_hms_opt(23, 56, 0).unwrap();
assert_eq!("23:56".parse::<NaiveTime>(), Ok(t));

assert!("foo".parse::<NaiveTime>().is_err());
Sourceยง

impl FromStr for FixedOffset

Parsing a str into a FixedOffset uses the format %z.

Sourceยง

impl FromStr for Oid

Sourceยง

impl FromStr for Ipv4Net

Sourceยง

impl FromStr for Ipv6Net

Sourceยง

impl FromStr for BigInt

Sourceยง

impl FromStr for JsString

Sourceยง

impl FromStr for js_sys::Number

Sourceยง

impl FromStr for mime::Mime

Sourceยง

impl FromStr for proc_macro2::Literal

Sourceยง

impl FromStr for proc_macro2::TokenStream

Attempts to break the string into tokens and parse those tokens into a token stream.

May fail for a number of reasons, for example, if the string contains unbalanced delimiters or characters not existing in the language.

NOTE: Some errors may cause panics instead of returning LexError. We reserve the right to change these errors into LexErrors later.

Sourceยง

impl FromStr for serde_json::number::Number

Sourceยง

impl FromStr for Url

Parse a string as an URL, without a base URL or encoding override.

Sourceยง

impl FromStr for Braced

Sourceยง

impl FromStr for Hyphenated

Sourceยง

impl FromStr for Simple

Sourceยง

impl FromStr for Urn

Sourceยง

impl FromStr for Uuid

ยง

impl FromStr for Algorithm

ยง

type Err = Error

ยง

impl FromStr for AnyConnectOptions

ยง

type Err = Error

ยง

impl FromStr for AnyKind

ยง

type Err = Error

ยง

impl FromStr for AssociatedData

ยง

type Err = Error

ยง

impl FromStr for Attribute

ยง

type Err = ParseError

ยง

impl FromStr for BlankNode

ยง

type Err = TermParseError

ยง

impl FromStr for Boolean

ยง

impl FromStr for Cookie<'static>

ยง

type Err = ParseError

ยง

impl FromStr for Date

ยง

type Err = ParseDateTimeError

ยง

impl FromStr for DateTime

ยง

type Err = ParseDateTimeError

ยง

impl FromStr for Datetime

ยง

type Err = DatetimeParseError

ยง

impl FromStr for DayTimeDuration

ยง

type Err = ParseDurationError

ยง

impl FromStr for Decimal

ยง

type Err = ParseDecimalError

ยง

impl FromStr for Double

ยง

impl FromStr for Duration

ยง

type Err = ParseDurationError

ยง

impl FromStr for Float

ยง

impl FromStr for GDay

ยง

type Err = ParseDateTimeError

ยง

impl FromStr for GMonth

ยง

type Err = ParseDateTimeError

ยง

impl FromStr for GMonthDay

ยง

type Err = ParseDateTimeError

ยง

impl FromStr for GYear

ยง

type Err = ParseDateTimeError

ยง

impl FromStr for GYearMonth

ยง

type Err = ParseDateTimeError

ยง

impl FromStr for GitUrl

ยง

type Err = GitUrlParseError

ยง

impl FromStr for HttpDate

ยง

type Err = Error

ยง

impl FromStr for Id

ยง

type Err = DecodeSliceError

ยง

impl FromStr for Integer

ยง

impl FromStr for Iri<String>

ยง

type Err = IriParseError

ยง

impl FromStr for IriRef<String>

ยง

type Err = IriParseError

ยง

impl FromStr for Key

ยง

type Err = ParseError

ยง

impl FromStr for Key

ยง

type Err = ParseError

ยง

impl FromStr for KeyId

ยง

type Err = Error

ยง

impl FromStr for Language

ยง

type Err = ParseError

ยง

impl FromStr for LanguageTag<String>

ยง

type Err = LanguageTagParseError

ยง

impl FromStr for Level

ยง

type Err = ParseLevelError

ยง

impl FromStr for Level

ยง

type Err = ()

ยง

impl FromStr for LevelFilter

ยง

type Err = ParseLevelFilterError

ยง

impl FromStr for Literal

ยง

type Err = TermParseError

ยง

impl FromStr for Map<String, Value>

ยง

type Err = Error

ยง

impl FromStr for Mime

ยง

type Err = MimeParsingError

ยง

impl FromStr for Month

ยง

type Err = InvalidVariant

ยง

impl FromStr for Name

ยง

type Err = InvalidNameError

ยง

impl FromStr for Name

ยง

type Err = InvalidNameError

ยง

impl FromStr for NamedNode

ยง

type Err = TermParseError

ยง

impl FromStr for Output

ยง

type Err = Error

ยง

impl FromStr for ParamsString

ยง

type Err = Error

ยง

impl FromStr for PasswordHashString

ยง

type Err = Error

ยง

impl FromStr for PredefinedColorSpace

ยง

type Err = ()

ยง

impl FromStr for Quad

ยง

type Err = TermParseError

ยง

impl FromStr for Query

ยง

type Err = SparqlSyntaxError

ยง

impl FromStr for Query

ยง

type Err = SparqlSyntaxError

ยง

impl FromStr for Regex

ยง

type Err = Error

ยง

impl FromStr for Regex

ยง

type Err = Error

ยง

impl FromStr for Region

ยง

type Err = ParseError

ยง

impl FromStr for Schedule

ยง

type Err = Error

ยง

impl FromStr for Scheme

ยง

type Err = ParseError

ยง

impl FromStr for Script

ยง

type Err = ParseError

ยง

impl FromStr for SegmentId

ยง

type Err = SegmentIdParseError

ยง

impl FromStr for SqliteAutoVacuum

ยง

type Err = Error

ยง

impl FromStr for SqliteConnectOptions

ยง

type Err = Error

ยง

impl FromStr for SqliteJournalMode

ยง

type Err = Error

ยง

impl FromStr for SqliteLockingMode

ยง

type Err = Error

ยง

impl FromStr for SqliteSynchronous

ยง

type Err = Error

ยง

impl FromStr for SubdivisionId

ยง

type Err = ParseError

ยง

impl FromStr for SubdivisionSuffix

ยง

type Err = ParseError

ยง

impl FromStr for Subtag

ยง

type Err = ParseError

ยง

impl FromStr for Subtag

ยง

type Err = ParseError

ยง

impl FromStr for Targets

ยง

type Err = ParseError

ยง

impl FromStr for Term

ยง

type Err = TermParseError

ยง

impl FromStr for Time

ยง

type Err = ParseDateTimeError

ยง

impl FromStr for Triple

ยง

type Err = TermParseError

ยง

impl FromStr for Update

ยง

type Err = SparqlSyntaxError

ยง

impl FromStr for Update

ยง

type Err = SparqlSyntaxError

ยง

impl FromStr for UriTemplateString

ยง

type Err = Error

ยง

impl FromStr for Utf8PathBuf

ยง

impl FromStr for Value

ยง

type Err = Error

ยง

impl FromStr for Variable

ยง

type Err = TermParseError

ยง

impl FromStr for Variant

ยง

type Err = ParseError

ยง

impl FromStr for Weekday

ยง

type Err = InvalidVariant

ยง

impl FromStr for YearMonthDuration

ยง

type Err = ParseDurationError

ยง

impl<A> FromStr for Tendril<UTF8, A>
where A: Atomicity,

ยง

type Err = ()

Sourceยง

impl<S> FromStr for Alpha<Rgb<S, u8>, u8>

Sourceยง

impl<S> FromStr for Rgb<S, u8>

ยง

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

ยง

type Err = <S as FromStr>::Err

ยง

impl<S> FromStr for RiAbsoluteString<S>
where S: Spec,

ยง

type Err = Error

ยง

impl<S> FromStr for RiFragmentString<S>
where S: Spec,

ยง

type Err = Error

ยง

impl<S> FromStr for RiQueryString<S>
where S: Spec,

ยง

type Err = Error

ยง

impl<S> FromStr for RiReferenceString<S>
where S: Spec,

ยง

type Err = Error

ยง

impl<S> FromStr for RiRelativeString<S>
where S: Spec,

ยง

type Err = Error

ยง

impl<S> FromStr for RiString<S>
where S: Spec,

ยง

type Err = Error

ยง

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

ยง

type Err = <S as FromStr>::Err

ยง

impl<const MIN: i8, const MAX: i8> FromStr for RangedI8<MIN, MAX>

ยง

type Err = ParseIntError

ยง

impl<const MIN: i16, const MAX: i16> FromStr for RangedI16<MIN, MAX>

ยง

type Err = ParseIntError

ยง

impl<const MIN: i32, const MAX: i32> FromStr for RangedI32<MIN, MAX>

ยง

type Err = ParseIntError

ยง

impl<const MIN: i64, const MAX: i64> FromStr for RangedI64<MIN, MAX>

ยง

type Err = ParseIntError

ยง

impl<const MIN: i128, const MAX: i128> FromStr for RangedI128<MIN, MAX>

ยง

type Err = ParseIntError

ยง

impl<const MIN: isize, const MAX: isize> FromStr for RangedIsize<MIN, MAX>

ยง

type Err = ParseIntError

ยง

impl<const MIN: u8, const MAX: u8> FromStr for RangedU8<MIN, MAX>

ยง

type Err = ParseIntError

ยง

impl<const MIN: u16, const MAX: u16> FromStr for RangedU16<MIN, MAX>

ยง

type Err = ParseIntError

ยง

impl<const MIN: u32, const MAX: u32> FromStr for RangedU32<MIN, MAX>

ยง

type Err = ParseIntError

ยง

impl<const MIN: u64, const MAX: u64> FromStr for RangedU64<MIN, MAX>

ยง

type Err = ParseIntError

ยง

impl<const MIN: u128, const MAX: u128> FromStr for RangedU128<MIN, MAX>

ยง

type Err = ParseIntError

ยง

impl<const MIN: usize, const MAX: usize> FromStr for RangedUsize<MIN, MAX>

ยง

type Err = ParseIntError

ยง

impl<const N: usize> FromStr for TinyAsciiStr<N>

ยง

type Err = ParseError