Can I use strum to convert a string to f64?











up vote
0
down vote

favorite












I am refactoring a small stack based language I wrote and decided I would have a parser phase separated from the execution phase and as a result I would parse strings to a Token enum. I tried using strum to do this, here is the smallest example I could manage:



extern crate strum; // 0.11.0
#[macro_use]
extern crate strum_macros; // 0.11.0

#[derive(EnumString)]
enum Token {
#[strum(default="true")]
Number(f64)
}

fn main() {
}


Basically, what this should do is if nothing is matched, default to parsing a float. So, convert anything it is given to float in this case. Which gave:



error[E0277]: the trait bound `f64: std::convert::From<&str>` is not satisfied
--> src/main.rs:5:10
|
5 | #[derive(EnumString)]
| ^^^^^^^^^^ the trait `std::convert::From<&str>` is not implemented for `f64`
|
= help: the following implementations were found:
<f64 as std::convert::From<u32>>
<f64 as std::convert::From<i32>>
<f64 as std::convert::From<f32>>
<f64 as std::convert::From<i8>>
and 3 others
= note: required because of the requirements on the impl of `std::convert::Into<f64>` for `&str`


I also tried adding a impl for the conversion:



extern crate strum;
#[macro_use]
extern crate strum_macros;

impl<'a> From<&'a str> for f64 {
#[inline]
fn from(s: &'a str) -> Self {
// See footnote [1] for why conversion is done this way.
s.parse::<f64>().unwrap_or(0.0).to_owned();
}
}

#[derive(EnumString)]
enum Token {
#[strum(default="true")]
Number(f64)
}

fn main() {
}


However, this gives:



error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
--> src/main.rs:5:1
|
5 | impl<'a> From<&'a str> for f64 {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ impl doesn't use types inside crate
|
= note: the impl does not reference any types defined in this crate
= note: define and implement a trait or new type instead


Because I use strum I could not put this on Rust Playground, but the Cargo.toml is:



[package]
name = "strum_test"
version = "0.1.0"

[dependencies]
strum = "0.11.0"
strum_macros = "0.11.0"


And the file I edited was in strum_test/src/main.rs. Is there a way to handle this behavior in strum, or is there at least another graceful way of handling this conversion from &str to enum Token?






1 In the language by design is supposed to be hard to make an error. Does it make sense to convert, for instance, "lol" to 0? Not really, but my language does it anyway. More information is given in the CodeReview link.








share|improve this question
























  • The usual solution to implement an external trait for an external type is to use a newtype, e.g. struct Float(f64). You can then implement From for Float, and use Float in your enum.
    – Sven Marnach
    Nov 12 at 11:04










  • @SvenMarnach Thanks! That seemed to do the trick! If you want, you can post it as an answer and I'll accept. (I just posted all the code that I ended up writing for reference).
    – Dair
    Nov 12 at 22:22

















up vote
0
down vote

favorite












I am refactoring a small stack based language I wrote and decided I would have a parser phase separated from the execution phase and as a result I would parse strings to a Token enum. I tried using strum to do this, here is the smallest example I could manage:



extern crate strum; // 0.11.0
#[macro_use]
extern crate strum_macros; // 0.11.0

#[derive(EnumString)]
enum Token {
#[strum(default="true")]
Number(f64)
}

fn main() {
}


Basically, what this should do is if nothing is matched, default to parsing a float. So, convert anything it is given to float in this case. Which gave:



error[E0277]: the trait bound `f64: std::convert::From<&str>` is not satisfied
--> src/main.rs:5:10
|
5 | #[derive(EnumString)]
| ^^^^^^^^^^ the trait `std::convert::From<&str>` is not implemented for `f64`
|
= help: the following implementations were found:
<f64 as std::convert::From<u32>>
<f64 as std::convert::From<i32>>
<f64 as std::convert::From<f32>>
<f64 as std::convert::From<i8>>
and 3 others
= note: required because of the requirements on the impl of `std::convert::Into<f64>` for `&str`


I also tried adding a impl for the conversion:



extern crate strum;
#[macro_use]
extern crate strum_macros;

impl<'a> From<&'a str> for f64 {
#[inline]
fn from(s: &'a str) -> Self {
// See footnote [1] for why conversion is done this way.
s.parse::<f64>().unwrap_or(0.0).to_owned();
}
}

#[derive(EnumString)]
enum Token {
#[strum(default="true")]
Number(f64)
}

fn main() {
}


However, this gives:



error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
--> src/main.rs:5:1
|
5 | impl<'a> From<&'a str> for f64 {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ impl doesn't use types inside crate
|
= note: the impl does not reference any types defined in this crate
= note: define and implement a trait or new type instead


Because I use strum I could not put this on Rust Playground, but the Cargo.toml is:



[package]
name = "strum_test"
version = "0.1.0"

[dependencies]
strum = "0.11.0"
strum_macros = "0.11.0"


And the file I edited was in strum_test/src/main.rs. Is there a way to handle this behavior in strum, or is there at least another graceful way of handling this conversion from &str to enum Token?






1 In the language by design is supposed to be hard to make an error. Does it make sense to convert, for instance, "lol" to 0? Not really, but my language does it anyway. More information is given in the CodeReview link.








share|improve this question
























  • The usual solution to implement an external trait for an external type is to use a newtype, e.g. struct Float(f64). You can then implement From for Float, and use Float in your enum.
    – Sven Marnach
    Nov 12 at 11:04










  • @SvenMarnach Thanks! That seemed to do the trick! If you want, you can post it as an answer and I'll accept. (I just posted all the code that I ended up writing for reference).
    – Dair
    Nov 12 at 22:22















up vote
0
down vote

favorite









up vote
0
down vote

favorite











I am refactoring a small stack based language I wrote and decided I would have a parser phase separated from the execution phase and as a result I would parse strings to a Token enum. I tried using strum to do this, here is the smallest example I could manage:



extern crate strum; // 0.11.0
#[macro_use]
extern crate strum_macros; // 0.11.0

#[derive(EnumString)]
enum Token {
#[strum(default="true")]
Number(f64)
}

fn main() {
}


Basically, what this should do is if nothing is matched, default to parsing a float. So, convert anything it is given to float in this case. Which gave:



error[E0277]: the trait bound `f64: std::convert::From<&str>` is not satisfied
--> src/main.rs:5:10
|
5 | #[derive(EnumString)]
| ^^^^^^^^^^ the trait `std::convert::From<&str>` is not implemented for `f64`
|
= help: the following implementations were found:
<f64 as std::convert::From<u32>>
<f64 as std::convert::From<i32>>
<f64 as std::convert::From<f32>>
<f64 as std::convert::From<i8>>
and 3 others
= note: required because of the requirements on the impl of `std::convert::Into<f64>` for `&str`


I also tried adding a impl for the conversion:



extern crate strum;
#[macro_use]
extern crate strum_macros;

impl<'a> From<&'a str> for f64 {
#[inline]
fn from(s: &'a str) -> Self {
// See footnote [1] for why conversion is done this way.
s.parse::<f64>().unwrap_or(0.0).to_owned();
}
}

#[derive(EnumString)]
enum Token {
#[strum(default="true")]
Number(f64)
}

fn main() {
}


However, this gives:



error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
--> src/main.rs:5:1
|
5 | impl<'a> From<&'a str> for f64 {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ impl doesn't use types inside crate
|
= note: the impl does not reference any types defined in this crate
= note: define and implement a trait or new type instead


Because I use strum I could not put this on Rust Playground, but the Cargo.toml is:



[package]
name = "strum_test"
version = "0.1.0"

[dependencies]
strum = "0.11.0"
strum_macros = "0.11.0"


And the file I edited was in strum_test/src/main.rs. Is there a way to handle this behavior in strum, or is there at least another graceful way of handling this conversion from &str to enum Token?






1 In the language by design is supposed to be hard to make an error. Does it make sense to convert, for instance, "lol" to 0? Not really, but my language does it anyway. More information is given in the CodeReview link.








share|improve this question















I am refactoring a small stack based language I wrote and decided I would have a parser phase separated from the execution phase and as a result I would parse strings to a Token enum. I tried using strum to do this, here is the smallest example I could manage:



extern crate strum; // 0.11.0
#[macro_use]
extern crate strum_macros; // 0.11.0

#[derive(EnumString)]
enum Token {
#[strum(default="true")]
Number(f64)
}

fn main() {
}


Basically, what this should do is if nothing is matched, default to parsing a float. So, convert anything it is given to float in this case. Which gave:



error[E0277]: the trait bound `f64: std::convert::From<&str>` is not satisfied
--> src/main.rs:5:10
|
5 | #[derive(EnumString)]
| ^^^^^^^^^^ the trait `std::convert::From<&str>` is not implemented for `f64`
|
= help: the following implementations were found:
<f64 as std::convert::From<u32>>
<f64 as std::convert::From<i32>>
<f64 as std::convert::From<f32>>
<f64 as std::convert::From<i8>>
and 3 others
= note: required because of the requirements on the impl of `std::convert::Into<f64>` for `&str`


I also tried adding a impl for the conversion:



extern crate strum;
#[macro_use]
extern crate strum_macros;

impl<'a> From<&'a str> for f64 {
#[inline]
fn from(s: &'a str) -> Self {
// See footnote [1] for why conversion is done this way.
s.parse::<f64>().unwrap_or(0.0).to_owned();
}
}

#[derive(EnumString)]
enum Token {
#[strum(default="true")]
Number(f64)
}

fn main() {
}


However, this gives:



error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
--> src/main.rs:5:1
|
5 | impl<'a> From<&'a str> for f64 {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ impl doesn't use types inside crate
|
= note: the impl does not reference any types defined in this crate
= note: define and implement a trait or new type instead


Because I use strum I could not put this on Rust Playground, but the Cargo.toml is:



[package]
name = "strum_test"
version = "0.1.0"

[dependencies]
strum = "0.11.0"
strum_macros = "0.11.0"


And the file I edited was in strum_test/src/main.rs. Is there a way to handle this behavior in strum, or is there at least another graceful way of handling this conversion from &str to enum Token?






1 In the language by design is supposed to be hard to make an error. Does it make sense to convert, for instance, "lol" to 0? Not really, but my language does it anyway. More information is given in the CodeReview link.





rust






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 22:52









Shepmaster

145k11278412




145k11278412










asked Nov 11 at 22:43









Dair

11.7k54172




11.7k54172












  • The usual solution to implement an external trait for an external type is to use a newtype, e.g. struct Float(f64). You can then implement From for Float, and use Float in your enum.
    – Sven Marnach
    Nov 12 at 11:04










  • @SvenMarnach Thanks! That seemed to do the trick! If you want, you can post it as an answer and I'll accept. (I just posted all the code that I ended up writing for reference).
    – Dair
    Nov 12 at 22:22




















  • The usual solution to implement an external trait for an external type is to use a newtype, e.g. struct Float(f64). You can then implement From for Float, and use Float in your enum.
    – Sven Marnach
    Nov 12 at 11:04










  • @SvenMarnach Thanks! That seemed to do the trick! If you want, you can post it as an answer and I'll accept. (I just posted all the code that I ended up writing for reference).
    – Dair
    Nov 12 at 22:22


















The usual solution to implement an external trait for an external type is to use a newtype, e.g. struct Float(f64). You can then implement From for Float, and use Float in your enum.
– Sven Marnach
Nov 12 at 11:04




The usual solution to implement an external trait for an external type is to use a newtype, e.g. struct Float(f64). You can then implement From for Float, and use Float in your enum.
– Sven Marnach
Nov 12 at 11:04












@SvenMarnach Thanks! That seemed to do the trick! If you want, you can post it as an answer and I'll accept. (I just posted all the code that I ended up writing for reference).
– Dair
Nov 12 at 22:22






@SvenMarnach Thanks! That seemed to do the trick! If you want, you can post it as an answer and I'll accept. (I just posted all the code that I ended up writing for reference).
– Dair
Nov 12 at 22:22














1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










Based off of Sven Marnach's comment I added a struct Float(f64). Here is all the code for reference:



extern crate strum;
#[macro_use]
extern crate strum_macros;

struct Float(f64);

impl<'a> From<&'a str> for Float {
#[inline]
fn from(s: &'a str) -> Self {
Float(s.parse::<f64>().unwrap_or(0.0).to_owned())
}
}

#[derive(EnumString)]
enum Token {
#[strum(default="true")]
Number(Float)
}

fn main() {
}





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53253983%2fcan-i-use-strum-to-convert-a-string-to-f64%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    Based off of Sven Marnach's comment I added a struct Float(f64). Here is all the code for reference:



    extern crate strum;
    #[macro_use]
    extern crate strum_macros;

    struct Float(f64);

    impl<'a> From<&'a str> for Float {
    #[inline]
    fn from(s: &'a str) -> Self {
    Float(s.parse::<f64>().unwrap_or(0.0).to_owned())
    }
    }

    #[derive(EnumString)]
    enum Token {
    #[strum(default="true")]
    Number(Float)
    }

    fn main() {
    }





    share|improve this answer

























      up vote
      1
      down vote



      accepted










      Based off of Sven Marnach's comment I added a struct Float(f64). Here is all the code for reference:



      extern crate strum;
      #[macro_use]
      extern crate strum_macros;

      struct Float(f64);

      impl<'a> From<&'a str> for Float {
      #[inline]
      fn from(s: &'a str) -> Self {
      Float(s.parse::<f64>().unwrap_or(0.0).to_owned())
      }
      }

      #[derive(EnumString)]
      enum Token {
      #[strum(default="true")]
      Number(Float)
      }

      fn main() {
      }





      share|improve this answer























        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        Based off of Sven Marnach's comment I added a struct Float(f64). Here is all the code for reference:



        extern crate strum;
        #[macro_use]
        extern crate strum_macros;

        struct Float(f64);

        impl<'a> From<&'a str> for Float {
        #[inline]
        fn from(s: &'a str) -> Self {
        Float(s.parse::<f64>().unwrap_or(0.0).to_owned())
        }
        }

        #[derive(EnumString)]
        enum Token {
        #[strum(default="true")]
        Number(Float)
        }

        fn main() {
        }





        share|improve this answer












        Based off of Sven Marnach's comment I added a struct Float(f64). Here is all the code for reference:



        extern crate strum;
        #[macro_use]
        extern crate strum_macros;

        struct Float(f64);

        impl<'a> From<&'a str> for Float {
        #[inline]
        fn from(s: &'a str) -> Self {
        Float(s.parse::<f64>().unwrap_or(0.0).to_owned())
        }
        }

        #[derive(EnumString)]
        enum Token {
        #[strum(default="true")]
        Number(Float)
        }

        fn main() {
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 12 at 22:21









        Dair

        11.7k54172




        11.7k54172






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53253983%2fcan-i-use-strum-to-convert-a-string-to-f64%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Xamarin.iOS Cant Deploy on Iphone

            Glorious Revolution

            Dulmage-Mendelsohn matrix decomposition in Python