Does this mean any type appointed to the alias MaxLocks
must implement the trait Get<T>
?
pub trait Get<T> {
/// Return the current value.
fn get() -> T;
}
type MaxLocks: Get<u32>;
Does this mean any type appointed to the alias MaxLocks
must implement the trait Get<T>
?
pub trait Get<T> {
/// Return the current value.
fn get() -> T;
}
type MaxLocks: Get<u32>;
The syntax is invalid.
error: free type alias without body
--> src/lib.rs:6:1
|
6 | type MaxLocks: Get<u32>;
| ^^^^^^^^^^^^^^^^^^^^^^^-
| |
| help: provide a definition for the type: `= <type>;`
It is defined here.
And used here
Aha, so it's part of a trait. That changes things quite a lot. It's an associated type. Whenever you implement the trait, you have to pick some type for the MaxLocks
type, and you can only pick types that implement the specified trait.
"The specific trait" being Get<T>
?
Yes.
A typical example for this in the standard library is IntoIterator
.
You can do something like
fn foo<I: IntoIterator<Item = u32>>(x: I) {
let y = x.into_iter();
let mut r: u32 = 0;
y.for_each(|item| r += item);
}
The fact that we can call for_each
on y
relies on the fact that y
is an iterator (of u32
s). The type of y
is the return type of I::into_iter
, which is an associated type in the IntoIterator
trait.
pub trait IntoIterator {
type Item;
type IntoIter: Iterator<Item = Self::Item>;
fn into_iter(self) -> Self::IntoIter;
}
the : Iterator<Item = Self::Item>
part if that associated type declaration is what makes sure that we do in fact get an iterator.
If the trait was something like
pub trait IntoIterator {
type IntoIter;
fn into_iter(self) -> Self::IntoIter;
}
instead, you’d need to put the bound for every user of the trait, so foo
would need to be written
fn foo<I: IntoIterator>(x: I)
where
I::IntoIter: Iterator<Item = u32>,
{
let y = x.into_iter();
let mut r: u32 = 0;
y.for_each(|item| r += item);
}
The Item
type in IntoIterator
is a convenience feature allowing us to specify the item type of the resulting iterator in an IntoIterator<Item = ...>
bound.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.