struct or structure 是一个自定义的数据类型,允许你包装和命名多个相关联的值,从而形成一个有意义的组合。如果你熟悉一门面向对象语言,struct就像对象中的数据属性。在本章中,我们会对元组和结构体进行对比和对照。还将演示如何定义和实现实例化结构体,并讨论如何定义关联函数,特别是被称为方法的那种关联函数,以指定与结构体类型相关的行为。你可以在程序中基于结构体和枚举(enum)(在第六章中介绍)创建新类型,以充分利用Rust的编译时类型检查。
fnmain() { lets1 = gives_ownership(); // gives_ownership moves its return // value into s1
lets2 = String::from("hello"); // s2 comes into scope
lets3 = takes_and_gives_back(s2); // s2 is moved into // takes_and_gives_back, which also // moves its return value into s3 } // Here, s3 goes out of scope and is dropped. s2 was moved, so nothing // happens. s1 goes out of scope and is dropped.
fngives_ownership() ->String { // gives_ownership will move its // return value into the function // that calls it
letsome_string = String::from("yours"); // some_string comes into scope
some_string // some_string is returned and // moves out to the calling // function }
// This function takes a String and returns one fntakes_and_gives_back(a_string: String) ->String { // a_string comes into // scope
a_string // a_string is returned and moves out to the calling function }
Listing 4-4: Transferring ownership of return values
#![allow(unused)] fnmain() { // So we’re doing something complicated here, long enough that we need // multiple lines of comments to do it! Whew! Hopefully, this comment will // explain what’s going on. }
thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 10', src/main.rs:19:19 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace