basic/compound-type/struct #1154
Replies: 15 comments 24 replies
-
struct Struct{
a:i32,
b:String,
}
fn make() -> Struct{
Struct{
a:3,
b:String::from("hello"),
}
}
fn main(){
let a = make();
} 在这里,我make出来的struct的所有权最后给了a,那么是否说明struct中的内容(它的a和b)默认是在堆中呢? |
Beta Was this translation helpful? Give feedback.
-
#[derive(Debug)]
struct Person{
name: String,
age: i32,
}
let mut p = Person{name: String::from("junmajinlong"), age: 23,};
let t = &mut p;
let name= t.name; 有个疑惑,这段代码中,有点不太理解,t 是p 的可变引用,t 本身是不可变变量,let name = t.name 确实不对。 如果后面改成 下面同时多个可变借用也是对的 let s= &mut t.name;
println!("s: {}", s) 而且如果 let name = &mut t.name
println!("t: {:?}, s: {}", t, s) 又会报错如下: |
Beta Was this translation helpful? Give feedback.
-
访问结构体字段,当更新了user1的email字段后,原本email指向的内存会被自动释放吗?"[email protected]"这个字符串还在吗? let mut user1 = User {
email: String::from("[email protected]"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
user1.email = String::from("[email protected]"); |
Beta Was this translation helpful? Give feedback.
-
fn main() {
} 为什么user1不可以修改email,而通过abc1对象就可以修改email |
Beta Was this translation helpful? Give feedback.
-
请问这个代码: let f1_length = &f1.data.len(); .运算符的优先级是高于&的吧,这样f1_length不就是len()函数返回值的引用吗?但是这个返回值不是一个临时变量吗?还是说这里f1_length直接就拥有了返回的变量? let len1 = &f.data.len();
let len2 = &f.data.len();
let addr1 = len1 as *const usize as usize;
let addr2 = len2 as *const usize as usize; 发现addr1和addr2的值是不一样的,说明它们引用的是不同的变量。那返回并被引用的这两个usize变量在哪里呢? |
Beta Was this translation helpful? Give feedback.
-
关于结构体更新语法这一节,如何拿到旧对象中没有被转移的字段呢?示例代码: struct Struct {
a: String,
b: String,
}
impl Struct {
fn from(from: Self) -> Self {
Struct {
a: "new_a".to_string(),
..from
}
}
}
fn main() {
let v1 = Struct {
a: "old_a".to_string(),
b: "b".to_string(),
};
let v2 = Struct::from(v1);
// 请问之后的代码如何拿到v1里边的a字段呢?
// todo: 想使用 old_a
} |
Beta Was this translation helpful? Give feedback.
-
请问在什么情况下需要给结构体内部字段加 |
Beta Was this translation helpful? Give feedback.
-
dbg! 真好用 |
Beta Was this translation helpful? Give feedback.
-
fn build_user(email: String, username: String) -> User { |
Beta Was this translation helpful? Give feedback.
-
#[derive(Debug)]
struct File {
name: String,
data: Vec<u8>,
}
fn main() {
let f1 = File {
name: String::from("f1.txt"),
data: Vec::new(),
};
let f1_name = &f1.name;
let f1_length = &f1.data.len();
println!("{:?}", f1);
println!("{} is {} bytes long", f1_name, f1_length);
} 这段代码中, |
Beta Was this translation helpful? Give feedback.
-
请问下, 结构体支持成员的类型是函数吗? |
Beta Was this translation helpful? Give feedback.
-
结构体可以 解构吗? let {age, name} = person; |
Beta Was this translation helpful? Give feedback.
-
天下无敌的剑士往往也因为他有一柄无双之剑,盖聂? |
Beta Was this translation helpful? Give feedback.
-
basic/compound-type/struct
https://course.rs/basic/compound-type/struct.html
Beta Was this translation helpful? Give feedback.
All reactions