Rust中如何保证任意struct可通过::new()泛型构造?
如何保证能通过
WhateverStruct::new()构造任意struct? TL;DR:如何保证我可以通过WhateverStruct::new()构造任意struct?
如下代码无法运行:
trait Constructable { fn new() -> Self; } struct Foo { bar: u8 /* 其他可能包含的字段 */ } impl Constructable for Foo { fn new(baz: u8) -> Self { return Self { bar: baz }; } }
原因是new()不符合Constructable trait的定义。
背景
我正在通过实现链表学习Rust。
在C++、TypeScript等语言中,编写链表时无需关心存储的数据类型是否有构造函数:
template<typename T> class LinkedListNode<T> { public: LinkedListNode(T data) { // 这个类不关心T来自哪里、谁构造的、怎么构造的 this->data = data; } T data; }; template<typename T> class LinkedList<T> { public: LinkedList() { this->head = nullptr; } /* 链表的其他操作 */ std::shared_ptr<LinkedListNode<T>> head; };
在Rust中,struct默认没有构造函数的概念,因此无法保证WhateverStruct::new()一定存在。
于是我定义了一个trait来确保它存在:
trait Constructible { fn new() -> Self; }
之后我编写了链表的结构:
struct LinkedListNode<'a, T> { // 为生命周期做了不少调整 data: T, next: Option<&'a LinkedListNode<'a, T>> // 类似C++中的指针,避免结构体无限递归 } struct LinkedList<'a, T> { // 这里也做了很多调整 head: Option<LinkedListNode<'a, T>> }
目前一切正常。现在我想测试这个保证构造函数存在的方案,于是创建了一个要存入链表的新类型:
struct Foo { bar: u8 /* 其他可能包含的字段 */ } impl<T> Constructable for Foo { fn new() -> Self { // 暂时留空 } }
暂时先不管Foo的具体内容,假设我需要传入参数构造它,此时出现了问题:
impl Constructible for Foo { fn new(baz: u8) -> Self { // <- 期望0个参数,实际传入1个 return Foo { bar: baz }; } }
此时new函数不再符合Constructible trait的定义。
我该怎么做才能保证可以构造任意struct?
补充说明
有评论者提到:
I'm not seeing any relationship between
Constructibleand the linked list, though.
我之前没说明为什么需要Constructible,现在补充如下:
impl<'a, T> Constructable for LinkedListNode<'a, T> where T: Constructable { fn new(/* T所需的任意参数 */) -> Self { return Self { T::new(/* T所需的任意参数 */), None }; } } fn main() { let l: LinkedList::<Foo> = LinkedList::new(); l.push(/* 构造Foo所需的参数 */); }
内容的提问来源于stack exchange,提问作者404 Name Not Found
相关产品推荐
相关产品推荐

