list - 列出 Rust 中的不同类型

标签 list inheritance types rust

这个问题在这里已经有了答案:





How do I create a heterogeneous collection of objects?

(1 个回答)


1年前关闭。




在 C# 中,我可以创建一个列表并向其中添加不同类型的项目。只要他们继承基类。例如:

using System;
using System.Collections.Generic;

class Parent
{
    public int p;

    public Parent(int p)
    {
        this.p = p;
    }
}

class A : Parent
{
    public int a;

    public A(int p, int a) : base(p)
    {
        this.a = a;
    }
}

class B : Parent
{
    public int b;

    public B(int p, int b) : base(p)
    {
        this.b = b;
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<Parent> list = new List<Parent>();

        A a = new A(10, 20);
        B b = new B(30, 40);
        list.Add(a);
        list.Add(b);

        A l_a = list[0] as A;
        B l_b = list[1] as B;

        Console.WriteLine(String.Format("{0}, {1}", l_a.p, l_a.a)); // 10, 20
        Console.WriteLine(String.Format("{0}, {1}", l_b.p, l_b.b)); // 30, 40
    }
}

Rust 不是一种面向对象的编程语言,但我想知道是否可以实现类似的东西。有方法吗?

最佳答案

您可以创建 Enum并将其不同的变体存储在向量中。

示例:

use std::fmt::{Display, Formatter};

struct A {
    a: i32,
}

impl A {
    fn new(a: i32) -> Self {
        A { a }
    }
}

struct B {
    b: i32,
}

impl B {
    fn new(b: i32) -> Self {
        B { b }
    }
}

enum Parent {
    ChildA(i32, A),
    ChildB(i32, B),
}

impl Display for Parent {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Parent::ChildA(p, a) => write!(f, "{}, {}", p, a.a),
            Parent::ChildB(p, b) => write!(f, "{}, {}", p, b.b),
        }
    }
}

fn main() {
    let mut vec = Vec::new();

    let a = Parent::ChildA(10, A::new(20));
    let b = Parent::ChildB(30, B::new(40));

    vec.push(a);
    vec.push(b);

    let l_a = vec.get(0).unwrap();
    let l_b = vec.get(1).unwrap();

    println!("{}", l_a);
    println!("{}", l_b);
}

关于list - 列出 Rust 中的不同类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62299911/

相关文章:

java - List.addAll 正在复制 session 变量

c++ - 对于私有(private)继承,什么时候可以向上转型?

c# - 将泛型 T 的类型解析为 C# 中的特定接口(interface)

types - 接口(interface) block 中的 "Derived type is being used before it is defined"

c 版本的类名

list - 以功能风格将 elem 与下一个连接起来

python - 如何在 Python 中获取列表中的最后一个非空项?

html - Bootstrap 按钮悬停继承类

java - @MappedSuperclass和实现表

list - 什么是 Haskell 的 Stream Fusion