rust - 元组是否实现 `Copy` ?

标签 rust tuples

在 Rust Book 第 18 章中,他们给出了模式匹配中元组的示例。

fn print_coordinates(&(x, y): &(i32, i32)) {
    println!("Current location: ({}, {})", x, y);
}

fn main() {
    let point = (3, 5);
    print_coordinates(&point);   // point passed as reference
}

出于好奇,我试过不通过这样的引用。

fn print_coordinates((x, y): (i32, i32)) {
    println!("Current location: ({}, {})", x, y);
}

fn main() {
    let point = (3, 5);
    print_coordinates(point);   // point passed as value
    print_coordinates(point);   // point is still valid here
}

它编译并打印出坐标 2 次。

能否像其他原始数据类型(数字、 bool 值等)一样将元组传递给函数?

最佳答案

是的;根据 the docs ,这对于元数为 12 或更小的元组是正确的:

If every type inside a tuple implements one of the following traits, then a tuple itself also implements it.

Due to a temporary restriction in Rust's type system, these traits are only implemented on tuples of arity 12 or less. In the future, this may change.

关于rust - 元组是否实现 `Copy` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45847338/

相关文章:

rust - 如何修改 HashSet 中不属于哈希计算的属性?

generics - 在 Rust 中只为泛型结构编写一次特征绑定(bind)

python - 元组对列表到字典中

python - 使用键/元组对从字典中提取元组

rust - 返回结构的类型不匹配(预期 <K, V>,找到 <&K, &V>)

rust - 从通过迭代找到的 BTreeMap 或 BTreeSet 中删除项目

rust - 为什么 println! f32 和 f64 打印不同的输出?

python - 在一个元组内重复一个元组

python - 计算元组列表中项目的频率

python - 从外部函数调用元组作为另一个函数中的双变量