在 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/