什么是意义 rust 解除引用?[关闭]

gpnt7bae  于 2023-01-17  发布在  其他
关注(0)|答案(1)|浏览(123)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

3天前关闭。
Improve this question
我开始学习Rust,在Sushing中,我有hashmap3练习,编码如下

fn build_scores_table(results: String) -> HashMap<String, Team> {
    // The name of the team is the key and its associated struct is the value.
    let mut scores: HashMap<String, Team> = HashMap::new();

    for r in results.lines() {
        let v: Vec<&str> = r.split(',').collect();
        let team_1_name = v[0].to_string();
        let team_1_score: u8 = v[2].parse().unwrap();
        let team_2_name = v[1].to_string();
        let team_2_score: u8 = v[3].parse().unwrap();
        let t1 = scores.entry(team_1_name.clone()).or_insert(Team {
            name: team_1_name,
            goals_scored: 0,
            goals_conceded: 0,
        });
        t1.goals_scored += team_1_score;
        t1.goals_conceded += team_2_score;

        let t2 = scores.entry(team_2_name.clone()).or_insert(Team {
            name: team_2_name,
            goals_scored: 0,
            goals_conceded: 0,
        });
        t2.goals_conceded += team_1_score;
        t2.goals_scored += team_2_score;
        // TODO: Populate the scores table with details extracted from the
        // current line. Keep in mind that goals scored by team_1
        // will be the number of goals conceded from team_2, and similarly
        // goals scored by team_2 will be the number of goals conceded by
        // team_1.
    }
    println!("{:?}", scores);

    scores
}

但随后也找到了GitHub中其他铁 rust 开发和使用的答案

let t1 = scores.entry(team_1_name.clone()).or_insert(Team {
        name: team_1_name,
        goals_scored: 0,
        goals_conceded: 0,
    });
    (*t1).goals_scored += team_1_score;
    (*t1).goals_conceded += team_2_score;

    let t2 = scores.entry(team_2_name.clone()).or_insert(Team {
        name: team_2_name,
        goals_scored: 0,
        goals_conceded: 0,
    });
    (*t2).goals_conceded += team_1_score;
    (*t2).goals_scored += team_2_score;

这两个实现都能工作,并且通过了练习测试,但是在这里使用(*t1)有什么意义呢?抱歉问了这个愚蠢的问题,感谢您的帮助。

8zzbczxx

8zzbczxx1#

有时候,解引用是绝对必要的,比如在进行比较时:

let a = 1;
let b = &a;

assert_eq!(a, b); // no implementation for `{integer} == &{integer}`
assert_eq!(a, *b); // integer == integer

在其他情况下,解引用是隐式的,比如在进行函数调用时:

struct Example(i32);

impl Example {
    fn method(&self) -> bool {
        true
    }
}

fn main() {
   let e = Example(0);
   let r = &e;
   
   r.method(); // Doesn't matter if it's a reference, it all works out
   (*r).method(); // You could do this but it's ugly and unnecessary
}

通常这里少即是多,如果你不需要解引用,就不要去做。

相关问题