You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Rust中&Vec3无法相加的E0369错误?

问题解决:Rust中Vec3引用相加触发E0369错误

问题原因

你当前仅为Vec3值类型实现了Add trait,而apply_by_ref__st函数中传入的是&Vec3引用,Rust找不到针对两个&Vec3的加法实现,因此抛出E0369错误。

理想解决方案:为引用类型实现Add

更符合Rust惯例的方式是为&Vec3实现Add trait,这样既保留原有值类型的加法逻辑,又能支持引用直接相加,代码复用性更好,调用也更自然。

修改后的代码如下:

use std::ops::Add;

pub struct Vec3
{
    pub x: f64,
    pub y: f64,
    pub z: f64
}

// 为值类型实现Add
impl Add for Vec3
{
    type Output = Vec3;
    fn add(self, other: Vec3) -> Vec3
    {
        Vec3
        {
            x: self.x + other.x,
            y: self.y + other.y,
            z: self.z + other.z
        }
    }
}

// 为&Vec3实现Add,复用值类型的add逻辑
impl Add for &Vec3
{
    type Output = Vec3;
    fn add(self, other: &Vec3) -> Vec3
    {
        *self + *other
    }
}

impl Vec3
{
    pub fn apply_by_value__mbr(mut self, rhs:Vec3)
    {
        self = self + rhs;
    }
    pub fn apply_by_ref__mbr(mut self, rhs: &Vec3)
    {
        self = self + *rhs;
    }
    pub fn apply_by_value__st(lhs: Vec3, rhs:Vec3) -> Vec3
    {
        let mut temp: Vec3;
        temp = lhs + rhs;
        return temp;
    }
    pub fn apply_by_ref__st(v1: &Vec3, v2: &Vec3) -> Vec3
    {
        return v1 + v2; // 现在可以直接相加
    }
    pub fn print(self)
    {
        println!("x:{}, y:{}, z:{}", self.x, self.y, self.z);
    }
}

备选方案:修改调用处解引用

如果你不想新增运算符重载,也可以在apply_by_ref__st中对引用解引用,将其转为值类型后相加:

pub fn apply_by_ref__st(v1: &Vec3, v2: &Vec3) -> Vec3
{
    return *v1 + *v2;
}

方案对比

  • 第一种方案(为引用实现Add):更优雅,用户调用时无需手动解引用,符合Rust运算符重载的设计理念,同时支持值和引用两种场景的加法操作。
  • 第二种方案(解引用):代码改动小,但每次使用引用相加都需要手动解引用,不够便捷,尤其是在复杂表达式中会增加代码冗余。

内容的提问来源于stack exchange,提问作者user366312

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 08:43:29