Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
954 views
in Technique[技术] by (71.8m points)

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

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 C++ with non-const arguments) without an extra variable?

use std::fs::File;
use std::io;
use std::io::Read;

fn read_string(filename: &str) -> Result<String, io::Error> {
    let mut s = String::new();
    File::open(filename)?.read_to_string(&mut s)?;
    Ok(s)
}

fn main() {
    let s = read_string("tt.txt").expect("Wow");

    // let s2: String = s.chars().skip(0).take(s.len() -2).collect();

    println!(
        "{}",
        s.chars().skip(0).take(s.len() - 2).collect() as String
    );
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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::<String>()
    );
}

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

Other

You don't need to write read_string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...