创建新泛型结构的正确方法是什么? [英] What is the proper way to create a new generic struct?

查看:51
本文介绍了创建新泛型结构的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个可以初始化为 T 类型的通用结构.看起来像这样:

  pub struct MyStruct< T>{test_field:选项< T> ;,名称:字符串,年龄:i32,}impl MyStruct< T>{fn new(new_age:i32,new_name:String)->MyStruct< T>{MyStruct< T>{test_field:无,年龄:new_age,名称:new_name,}}} 

这似乎不起作用.除其他错误外,我得到:

 错误:链接的比较运算符需要括号->src/lib.rs:9:17|9 |MyStruct< T>{|^^^^^| 

解决方案

强烈推荐阅读 Rust编程语言 .它涵盖了这样的基础知识,Rust团队花费了大量时间来使其变得更好!具体来说,关于泛型的部分可能会在这里有所帮助./p>

实例化结构时,您无需使用< T> .将推断出 T 的类型.您需要在 impl 块上声明 T 是通用类型:

  struct MyStruct< T>{test_field:选项< T> ;,名称:字符串,年龄:i32,}impl TMyStruct< T>{//^^^fn new(new_age:i32,new_name:String)->MyStruct< T>{MyStruct {test_field:无,年龄:new_age,名称:new_name,}}} 

作为 = help:如果要指定类型参数,请使用`::< ...>`代替`< ...>`= help:或如果要指定fn参数,则使用`(...)`

我只在类型不明确时才看到这样的事情,这种情况很少发生.

I'm trying to make a generic struct that can be initialized to something of type T. It looks like this:

pub struct MyStruct<T> {
    test_field: Option<T>,
    name: String,
    age: i32,
}

impl MyStruct<T> {
    fn new(new_age: i32, new_name: String) -> MyStruct<T> {
        MyStruct<T> {
            test_field: None,
            age: new_age,
            name: new_name,
        }
    }
}

This doesn't seem to work. Among other errors, I get:

error: chained comparison operators require parentheses
 --> src/lib.rs:9:17
  |
9 |         MyStruct<T> {
  |                 ^^^^^
  |

I highly recommend reading The Rust Programming Language. It covers basics like this, and the Rust team spent a lot of time to make it good! Specifically, the section on generics would probably have helped here.

You don't need to use <T> when instantiating the struct. The type for T will be inferred. You will need to declare that T is a generic type on the impl block:

struct MyStruct<T> {
    test_field: Option<T>,
    name: String,
    age: i32,
}

impl<T> MyStruct<T> {
//  ^^^
    fn new(new_age: i32, new_name: String) -> MyStruct<T> {
        MyStruct {
            test_field: None,
            age: new_age,
            name: new_name,
        }
    }
}

As DK. points out, you could choose to specify the type parameter using the turbofish syntax (::<>):

MyStruct::<T> {
//      ^^^^^
    test_field: None,
    age: new_age,
    name: new_name,
}

Modern compiler versions actually tell you this now:

  = help: use `::<...>` instead of `<...>` if you meant to specify type arguments
  = help: or use `(...)` if you meant to specify fn arguments

I've only ever seen something like this when the types are ambiguous, which doesn't happen very often.

这篇关于创建新泛型结构的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆