Is there a syntax for type annotation inside an expression? (usage example: default value)

Is there a way to write type annotations directly in an expression, e.g. when using Default::default()

?

For example, in the following example, the compiler obviously cannot infer the type:

use std::default::Default;

#[deriving(Default, Show)]
struct Point{ x: int, y: int };

println!("Default Point: {}", Default::default())

      

The only solution I have found is to annotate the LHS type of the extra binding let

.

let p: Point = Default::default();
println!("Default Point: {}", p)

      

I was hoping that somehow it is possible to tell the compiler directly which version Default::default()

I want. Maybe something like this:

println!("Default Point: {}", Default::default() as Point)
println!("Default Point: {}", Default::default<Point>())
println!("Default Point: {}", Default<Point>::default())
println!("Default Point: {}", Point::default())

      

But none of them are valid syntax.

+3


source to share


1 answer


This is currently done in the standard library using helper functions such as from_str

.

The basic idea is that using a function allows you to enter a type parameter, which you can then use, for example:



use std::default::Default;

#[deriving(Default, Show)]
struct Point{ x: int, y: int }

fn default<T: Default>() -> T { Default::default() }

fn main() {
    println!("Default Point: {}", default::<Point>());
}

      

+5


source







All Articles