gpt4 book ai didi

rust - 有什么方法可以从结构中获取关联类型?

转载 作者:行者123 更新时间:2023-11-29 08:02:28 27 4
gpt4 key购买 nike

这段代码:

use std::collections::HashMap;

struct MyNode;
struct MyEdge;

struct Graph<N, E> {
h: HashMap<N, Vec<E>>,
}

type MyGraph = Graph<MyNode, MyEdge>;

fn main() {

let x: MyGraph::N;//XXX

println!("Results:")

}

编译失败,错误:

error[E0223]: ambiguous associated type
--> /home/xxx/.emacs.d/rust-playground/at-2017-07-26-164119/snippet.rs:21:12
|
21 | let x: MyGraph::N;
| ^^^^^^^^^^ ambiguous associated type
|
= note: specify the type using the syntax `<Graph<MyNode, MyEdge> as Trait>::N`

有没有办法得到NGraph<MyNode, MyEdge> 输入?

我创建了一个别名 ( type = ) 来避免重复节点类型定义,所以在标记为XXX的地方会很棒我不会写 let x: MyNode但是let x: expression with MyGraph as argument .

最佳答案

您的代码中没有关联的类型参数。 Associated types仅适用于特征,它允许您这样写:

trait Graph {
type Node;
type Edge;
}

特别是,结构中有普通类型参数(NE)。没有共同特征,您必须手动解析类型。无论如何,在这里做起来并不复杂。

struct GraphImpl<N, E> {
h: HashMap<N, Vec<E>>,
}

type MyGraph = GraphImpl<MyNode, MyEdge>;

let x: MyNode;

但是,如果您确实为您的结构实现此 Graph 特性:

impl<N, E> Graph for GraphImpl<N, E> {
type Node = N;
type Edge = E;
}

然后您可以检索关联的类型,如 this question 所示。 :

let x: <MyGraph as Graph>::Node;

Playground

关于rust - 有什么方法可以从结构中获取关联类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45329011/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com