官术网_书友最值得收藏!

Generic implementations

We can also write impl blocks for our generic types too, but it gets verbose here because of the extra generic type parameters, as we'll see. Let's implement a new() method on our Container<T> struct:

// generic_struct_impl.rs

struct Container<T> {
item: T
}

impl Container<T> {
fn new(item: T) -> Self {
Container { item }
}
}

fn main() {
// stuff
}

Let's compile this:

The error message cannot find our generic type T. When writing an impl block for any generic type, we need to declare the generic type parameter before using it within our type. T is just like a variable—a type variable—and we need to declare it. Therefore, we need to modify the implementation block a bit by adding <T> after impl, like so:

impl<T> Container<T> {
fn new(item: T) -> Self {
Container { item }
}
}

With that change, the preceding code compiles. The previous impl block  basically means that we are implementing these methods for all types T, which appear in Container<T>. This impl block is a generic implementation. Therefore, every concrete Container that ever gets generated will have these methods. Now, we could have also written a more specific impl block for Container<T> by putting any concrete type in place of T. This is what it would look like:

impl Container<u32> {
fn sum(item: u32) -> Self {
Container { item }
}
}

In the preceding code, we implemented a method called sum, which is only present on Container<u32> types. Here, we don't need the <T> after impl because of the presence of u32 as a concrete type. This is another nice property of impl blocks, which allows you to specialize generic types by implementing methods independently.

主站蜘蛛池模板: 大渡口区| 四平市| 赫章县| 博爱县| 阿克苏市| 昌平区| 合肥市| 确山县| 洞头县| 通河县| 德惠市| 长阳| 罗源县| 霍州市| 商南县| 汝南县| 塘沽区| 三门县| 深水埗区| 福贡县| 尉氏县| 盐山县| 德阳市| 灵寿县| 叙永县| 平阴县| 西畴县| 黑龙江省| 宽城| 铅山县| 尼勒克县| 莆田市| 武安市| 桓台县| 万源市| 镇雄县| 富平县| 疏勒县| 武强县| 滕州市| 个旧市|