Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide a type-annotation for `AsRef`?

Tags:

rust

The following code shows were the question originates. Since as_slice() is deprecated, as_ref() is suggested as replacement.

However, when using it in this context, a type annotation is required.

let s = "Hi";             // This is a string slice
// warning: use of deprecated item: use std::convert::AsRef<str> instead, #[warn(deprecated)] on by default
assert!(s.replace("Hi", "Ho").as_slice() == "Ho");
// tests/lang.rs:120:35: 120:43 error: type annotations required: cannot resolve `collections::string::String : core::convert::AsRef<_>` [E0283]
// assert!(s.replace("Hi", "Ho").as_ref() == "Ho");

How can I provide such a type-annotation ?. The only syntax I would find somewhat applicable is <MyType as AsRef>::as_ref(), but I don't know how to do that with an instance.

I am using rustc 1.0.0-nightly (be9bd7c93 2015-04-05) (built 2015-04-05).

like image 534
Byron Avatar asked Apr 15 '15 06:04

Byron


2 Answers

In your precise case of String and &str, the simplest is to use the Index syntax:

let s: String = "foo".to_string();
let slice: &str = &s[..]; // full range index

which in your case, would give:

let s = "Hi";
assert!(&s.replace("Hi", "Ho")[..] == "Ho");

However, for traits methods like as_ref(), you can also call them using the syntax:

Trait::method(obj); // equivalent to obj.method();

Which allow you to set the types parameters like this:

Trait::<T>::method(obj);

In your case, an alternate syntax would thus be:

let s = "Hi";
assert!(AsRef::<str>::as_ref(&s.replace("Hi", "Ho")) == "Ho");
like image 81
Levans Avatar answered Nov 04 '22 05:11

Levans


In this particular case, you don’t need any fanciness at all: String is comparable with &str (there is a PartialEq<&str> implementation on String), so you can just compare them directly:

let s = "Hi";
assert!(s.replace("Hi", "Ho") == "Ho");
// Or, if you prefer:
assert_eq!(s.replace("Hi", "Ho"), "Ho");

In real life you will not often need to call as_ref for reasons like this.

like image 25
Chris Morgan Avatar answered Nov 04 '22 03:11

Chris Morgan