Type must be known

I'm getting this error when I'm trying to pass a variable of type String to Command:: new

let output = Command::new(editor.as_ref()
   |                      -------^^^^^^--
   |                      |      |
   |                      |      cannot infer type for type parameter `T` declared on the trait `AsRef`
   |                             this method call resolves to `&T`
   = note: type must be known at this point

Couple of questions:

  1. How I am supposed to specify the type?
  2. Why is the type of String not inferred (as editor is of type String) and just passed as ref to the Command:: new ?
  3. Why is this type not inferred from the type of argument required for the Command:: new ?


The Command::new function can accept any type that implements the AsRef<OsStr> trait, and your call to as_ref() can also resolve to different types, since the type of editor may implement AsRef<T> for multiple different types T. This means that there could be multiple valid choices of T that satisfy both requirements, which would be ambiguous.

If editor is a String, consider using as_str() instead, which always returns a &str, making it unambiguous.

1 Like

Thank you.

1 Like