What is the difference between type casting by setting the type of a variable and using `as`?

前端 未结 2 1329
感动是毒
感动是毒 2021-01-25 21:01

What is the difference between these two cases? Why does the commented line compile but the last line in the main is incorrect?

How to cut string (substr in

2条回答
  •  忘了有多久
    2021-01-25 21:30

    Explicitly typing a variable is not a type cast.

    As thoroughly explained elsewhere, Iterator::collect requires knowing the concrete type to collect into.

    A type cast, such as that performed by as, requires converting from one type to another. You've specified the second type (String), but there's still no way for the compiler to deduce what the first type should be.

    Turbofish

    The syntax you want in today's Rust is the turbofish:

    use std::fs;
    
    fn main() {
        let s = fs::read_to_string("tt.txt").expect("Wow");
    
        println!(
            "{}",
            s.chars().skip(0).take(s.len() - 2).collect::()
        );
    }
    
    • How to put a type annotation in an iterator's collect statement?
    • What is the syntax: `instance.method::()`?

    Type Ascription

    As a nightly feature, you could also use the experimental type ascription:

    #![feature(type_ascription)]
    
    use std::fs;
    
    fn main() {
        let s = fs::read_to_string("tt.txt").expect("Wow");
    
        println!(
            "{}",
            s.chars().skip(0).take(s.len() - 2).collect(): String
        );
    }
    
    • What is type ascription?

    Other

    You don't need to write read_string.

    • What's the de-facto way of reading and writing files in Rust 1.x?

提交回复
热议问题