compound-types/tuple #188
Replies: 43 comments 5 replies
-
第3题为什么12个元素可以打印,13个元素就不能打印,这是哪里规定的 |
Beta Was this translation helpful? Give feedback.
-
变量不可以只定义不绑定值,第五题,元组可以只定义,不绑定值吗? |
Beta Was this translation helpful? Give feedback.
-
2022.11.14 Done. |
Beta Was this translation helpful? Give feedback.
-
done lala~ |
Beta Was this translation helpful? Give feedback.
-
fn main() {
// 1.
// let _t0: (u8, i16) = (0, -1);
// let _t1: (u8, (i16, u32)) = (0, (-1, 1));
// let t: (u8, u16, i64, &str, String) = (1u8, 2u16, 3i64, "hello", String::from(", world"));
// println!("Hello, world!");
// 2.
// let t = ("i", "am", "sunface");
// assert_eq!(t.1, "am");
// 3.
// let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
// println!("too long tuple: {}, {}, {}, {}", too_long_tuple.0, too_long_tuple.1, too_long_tuple.2, too_long_tuple.3);
// 4.
// let tup = (1, 6.4, "hello");
// let (x, z, y) = tup;
// assert_eq!(x, 1);
// assert_eq!(z, 6.4);
// assert_eq!(y, "hello");
// 5.
// let (x, y, z);
// (y, z, x) = (1, 2, 3);
// assert_eq!(x, 3);
// assert_eq!(y, 1);
// assert_eq!(z, 2);
// 6.
let (x, y) = sum_multiply((2, 3));
assert_eq!(x, 5);
assert_eq!(y, 6)
}
fn sum_multiply(nums: (i32, i32)) -> (i32, i32) {
(nums.0 + nums.1, nums.0 * nums.1)
} |
Beta Was this translation helpful? Give feedback.
-
有人在看吗?第三题可以分享下嘛? |
Beta Was this translation helpful? Give feedback.
-
3.🌟 过长的元组无法被打印输出 // 修复代码错误
fn main() {
let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
println!("too long tuple: {:?}", too_long_tuple);
} Rust标准库提供了Debug trait来支持打印元组,但是在超过12个元素的情况下,默认的Debug trait并没有实现,这导致了无法直接使用{:?}来打印超过12个元素的元组。 fn main() {
let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
println!("too long tuple: {:?}", too_long_tuple);
}
fn main() {
let too_long_tuple = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,13];
println!("too long tuple: {:?}", too_long_tuple);
} 3.手动实现元组内有13个元素时的Debug trait以支持打印 use std::fmt;
// 定义一个包含13个元素的元组结构体
struct ThirteenTuple(i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32);
// 为 ThirteenTuple 结构体实现 Debug trait
impl fmt::Debug for ThirteenTuple {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// 手动格式化元组中的每个元素,并将其写入到提供的 formatter 中
write!(f, "ThirteenTuple({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {})",
self.0, self.1, self.2, self.3, self.4, self.5, self.6, self.7, self.8,
self.9, self.10, self.11, self.12)
}
}
fn main() {
// 创建一个包含13个元素的元组
let too_long_tuple = ThirteenTuple(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
// 使用 {:?} 打印元组
println!("too long tuple: {:?}", too_long_tuple);
} |
Beta Was this translation helpful? Give feedback.
-
mark finished |
Beta Was this translation helpful? Give feedback.
-
compound-types/tuple
Learning Rust By Practice, narrowing the gap between beginner and skilled-dev with challenging examples, exercises and projects.
https://zh.practice.rs/compound-types/tuple.html
Beta Was this translation helpful? Give feedback.
All reactions