531 views|10 replies

6841

Posts

11

Resources
The OP
 

"Rust in Action" Learning Structures [Copy link]

Chapter 3 mainly talks about composite data types, starting with learning structures. First, I create the following code:

#[derive(Debug)]
struct File {
    name: String,
    data: Vec<u8>,
}
fn main() {
    let fl = File {
        name: String::from("fl.txt"),
        data: Vec::new(),
    };

    let fl_name = &fl.name;
    let fl_length = &fl.data.len();

    println!("{:?}",fl);
    println!("{} is {} bytes long!", fl_name, fl_length);
}

A structure is defined here in struct File, and then fl is instantiated in main, and then its .name, long is extracted and printed out.

This program contains a lot of new knowledge, and the author provides detailed explanations.

【Thoughts】

It is becoming increasingly difficult to learn now. If you don’t use them frequently, it will be difficult to learn these unfamiliar concepts.

This post is from Programming Basics

Latest reply

Come on! Follow us and learn   Details Published on 2024-4-28 15:09
 

6841

Posts

11

Resources
2
 

Use imple to add methods to the structure

Adding methods to structures seems to be a new thing since I started programming. The author uses a diagram to illustrate the classes in other languages and the addition of methods to structures in Rust. The purpose of both is the same.

In the following code, impl is used to improve the operation of a File:

#![allow(unused_variables)]

#[derive(Debug)]
struct File {
    name: String,
    data: Vec<u8>,
}

impl File {
    fn new(name: &str) -> File {
        File {
            name: String::from(name),
            data: Vec::new(),
        }
    }

    fn new_with_data(
        name: &str,
        data: &Vec<u8>,
    ) -> File {
        let mut f = File::new(name);
        f.data = data.clone();
        f
    }

    fn read(
        self: &File,
        save_to: &mut Vec<u8>,
    ) -> usize {
        let mut tmp = self.data.clone();
        let read_length = tmp.len();
        save_to.reserve(read_length);
        save_to.append(&mut tmp);
        read_length
    }
}

fn open(f: &mut File) -> bool {
    true
}

fn close(f: &mut File) -> bool {
    true
}


fn main() {
    let f3_data: Vec<u8> = vec![
        114,117,115,116, 33
    ];

    let mut f3 = File::new_with_data("2.txt", &f3_data);

    let mut buffer: Vec<u8> = vec![];

    open( &mut f3);
    let f3_length = f3.read(&mut buffer);
    close(&mut f3);

    let text = String::from_utf8_lossy(&buffer);


    println!("{:?}",f3);
    println!("{} is {} bytes long!", &f3.name, f3_length);
    println!("{}",text);
}

In this example, new and read methods are added to File, which makes operations more convenient.

This post is from Programming Basics
 
 
 

4771

Posts

12

Resources
3
 
I have a question about the structure, I don't understand it. S1 is declared, s2 is generated using s1 data, and then the basic types are copied, and the ownership of the composite type is also given to others. What is left of s1?
This post is from Programming Basics

Comments

I just learned this and I don't understand how to use it, but I feel that its method encapsulation is quite useful. I wrote several methods for a structure and never encountered it before.  Details Published on 2024-4-27 12:50
I just learned this and I don't understand how to use it, but I feel that its method encapsulation is quite useful. I wrote several methods for a structure and never encountered it before.  Details Published on 2024-4-26 21:37
 
 
 

6841

Posts

11

Resources
4
 
Azuma Simeng posted on 2024-4-26 18:09 I have a question about the structure, I don't understand it. S1 is declared, s2 is generated with s1 data, and then the basic types are copied, the ownership of the composite type...

I just learned this and I don't understand how to use it, but I feel that its method encapsulation is quite useful. I wrote several methods for a structure and never encountered it before.

This post is from Programming Basics
 
 
 

6841

Posts

11

Resources
5
 
Azuma Simeng posted on 2024-4-26 18:09 I have a question about the structure, I don't understand it. S1 is declared, s2 is generated with s1 data, and then the basic types are copied, the ownership of the composite type...

I learned a lesson today:

Note that the structural update syntax is just like assignment with = in that it moves data, just as we discussed in the “How variables interact with data (I): Moving” section. In this example, we can’t use user1 after creating user2 in general because the String in user1’s username field is moved into user2. If we assign new String values to both email and username of user2, and only use the active and sign_in_count values of user1, then user1 will still be valid after creating user2. The types of active and sign_in_count are types that implement the Copy trait, so the same behavior we discussed in the “How variables interact with data (II): Cloning” section applies.

This post is from Programming Basics

Comments

Always keep in mind your data type and the ownership of the passed in. It feels a bit difficult. I haven't reached that level yet. I will study it again.  Details Published on 2024-4-27 13:26
 
 
 

4771

Posts

12

Resources
6
 
Azuma Si Meng posted on 2024-4-26 18:09 I have a question about the structure, I don't understand it. S1 is declared, s2 is generated with s1 data, and then the basic types are copied, the ownership of the composite type...
I learned a saying today: Please note that the structure update syntax is like an assignment with =, because it moves data, just like we talked about in the "How variables and data interact (I): Move" section. In this example, we can't use user1 after creating user2 because the String in user1's username field is moved to user2. If we assign new String values to both email and username of user2, and only use the active and sign_in_count values of user1, then user1 will still be valid after user2 is created. The types of active and sign_in_count are types that implement the Copy trait, so the same behavior we discussed in the "How variables and data interact (Part 2): Cloning" section also applies.
Always keep in mind your data type and the ownership of the passed in. It feels a bit difficult~ I haven't reached that level yet. I'll study it more.
This post is from Programming Basics
 
 
 

731

Posts

4

Resources
7
 

The structure of the RUST language shared by the host should be similar to the content of the class in C++ and Java, and the definition form feels similar to JavaScript.

This post is from Programming Basics

Comments

The unique thing about Rust is that it is not like anyone else, but it is a little bit like everyone else.  Details Published on 2024-4-27 20:58
 
 
 

6841

Posts

11

Resources
8
 
chejm posted on 2024-4-27 14:33 The structure of the RUST language shared by the OP should be similar to the content of the class in C++ and Java, and the definition form feels similar to JavaScript

The unique thing about Rust is that it is not like anyone else, but it is a little bit like everyone else.

This post is from Programming Basics
 
 
 

1129

Posts

1

Resources
9
 

I have been busy these days and haven't gotten to the big brother part yet. I will temporarily set a flag for later verification.

This post is from Programming Basics

Comments

Come on, I started studying Chapter 4 today.  Details Published on 2024-4-28 11:33
 
 
 

6841

Posts

11

Resources
10
 
hellokitty_bean posted on 2024-4-28 09:44 I have been very busy these days and have not yet reached the big brother part. I will temporarily set a flag for later verification

come on

I started studying Chapter 4 today.

This post is from Programming Basics
 
 
 

7462

Posts

2

Resources
11
 

Come on! Follow us and learn

This post is from Programming Basics
 
Personal signature

默认摸鱼,再摸鱼。2022、9、28

 
 

Find a datasheet?

EEWorld Datasheet Technical Support

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list