- Mastering Rust
- Rahul Sharma Vesa Kaihlavirta
- 296字
- 2021-07-02 13:35:29
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.
- HTML5+CSS3+JavaScript從入門到精通:上冊(cè)(微課精編版·第2版)
- Java范例大全
- Redis入門指南(第3版)
- Vue.js 2 and Bootstrap 4 Web Development
- MySQL數(shù)據(jù)庫(kù)基礎(chǔ)實(shí)例教程(微課版)
- Go并發(fā)編程實(shí)戰(zhàn)
- Julia高性能科學(xué)計(jì)算(第2版)
- Java Web從入門到精通(第2版)
- 黑莓(BlackBerry)開(kāi)發(fā)從入門到精通
- Selenium WebDriver Practical Guide
- Python人工智能項(xiàng)目實(shí)戰(zhàn)
- R語(yǔ)言數(shù)據(jù)分析從入門到實(shí)戰(zhàn)
- Illustrator CS6中文版應(yīng)用教程(第二版)
- HTML5+CSS3+JavaScript案例實(shí)戰(zhàn)
- Hadoop MapReduce v2 Cookbook(Second Edition)