2

Supposing I have a function like this:

fn my<T: fmt::Debug, U>(x: T) {
    println!("{:?}", mem::size_of::<U>());
    println!("{:?}", x);
}

It depends on two types T and U. I have to specify the type U when I call the function my. On the other hand, the type T can be determined from passed x, so, it's logical, I can miss it in a call.

When I try:

my::<u8>(10);

I get the error:

error[E0107]: wrong number of type arguments: expected 2, found 1

What is the correct way to say to Rust compiler to get the type T from passed x and to pass U only in <...>?

1 Answer 1

4

In Rust, _ in a type position is used to ask the compiler to infer something:

let foo: Vec<_> = (1..10).map(|i| i.to_string()).collect();
//           ^ collect in a vector whose type should be obvious

This also works in your case:

my::<_, u8>(10);
//   ^ infer `T`

(Permalink to the playground)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.