gpt4 book ai didi

rust - Rust 宏中的意外标记

转载 作者:行者123 更新时间:2023-11-29 07:59:57 25 4
gpt4 key购买 nike

我正在尝试为我正在编写的一些自定义结构编写一个扩展为 impls 集合的宏。这是我的:

pub trait ComponentWise : Clone + Copy {
fn new(x: f32, y: f32, z: f32) -> Self;

fn x(&self) -> f32;
fn y(&self) -> f32;
fn z(&self) -> f32;

fn has_nans(&self) -> bool {
f32::is_nan(self.x()) ||
f32::is_nan(self.y()) ||
f32::is_nan(self.z())
}
}

macro_rules! component_wise_impls {
($T:ty) => {
impl ComponentWise for $T {
fn new(x: f32, y: f32, z: f32) -> $T {
let x: $T = $T { vals: [x, y, z] };
debug_assert!(!x.has_nans());
x
}
};
}

pub struct Vector {
pub vals: [f32; 3]
}

component_wise_impls!(Vector);

可悲的是,有人告诉我:

error: unexpected token: Vector

let x: $T = $T { vals: [x, y, z] };

我有点惊讶,因为我可以做 Vector { vals: [x, y, z] },我认为这正是 $T { vals: [x, y, z] }; 扩展为。有没有办法在宏中编写这个函数?

最佳答案

这是有效的:

macro_rules! component_wise_impls {
($T:ident) => {
impl ComponentWise for $T {
fn new(x: f32, y: f32, z: f32) -> $T {
let x: $T = $T { vals: [x, y, z] };
debug_assert!(!x.has_nans());
x
}
}
}
}

您不能在需要表达式的地方使用 ty

从这里page :

The interpolation $argument_name may appear in any location consistent with its fragment specifier (i.e., if it is specified as ident, it may be used anywhere an identifier is permitted).

正如 llogiq 指出的,你必须实现 xyz 方法,所以完整的代码是:

pub trait ComponentWise : Clone + Copy {
fn new(x: f32, y: f32, z: f32) -> Self;

fn x(&self) -> f32;
fn y(&self) -> f32;
fn z(&self) -> f32;

fn has_nans(&self) -> bool {
f32::is_nan(self.x()) ||
f32::is_nan(self.y()) ||
f32::is_nan(self.z())
}
}

macro_rules! component_wise_impls {
($T:ident) => {
impl ComponentWise for $T {
fn new(x: f32, y: f32, z: f32) -> $T {
let x: $T = $T { vals: [x, y, z] };
debug_assert!(!x.has_nans());
x
}

fn x(&self) -> f32 {
self.vals[0]
}

fn y(&self) -> f32 {
self.vals[1]
}

fn z(&self) -> f32 {
self.vals[2]
}
}
}
}

#[derive(Copy, Clone)]
pub struct Vector {
pub vals: [f32; 3]
}

component_wise_impls!(Vector);

关于rust - Rust 宏中的意外标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32440967/

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