構造体はフィールドと呼ばれる要素の集まり
構造体はフィールド名と型を持つフィールドを複数持つ
struct Member {
id: String,
name: String,
age: i32,
}
let m = struct Member {
id: String::from("A0101"),
name: String::from("Pochi"),
age: 12,
}
struct Member {
id: String,
name: String,
age: i32,
}
fn main(){
let m = Member {
id: String::from("A0101"),
name: String::from("Pochi"),
age: 12
};
println!("id={:?}", m.id);
println!("name={:?}", m.name);
println!("age={:?}", m.age);
}
struct Member {
id: String,
name: String,
age: i32,
}
fn main(){
let mut m = Member {
id: String::from("A0101"),
name: String::from("Pochi"),
age: 12
};
m.name = String::from("Pochi");
m.age = 14;
println!("id={:?}", m.id);
println!("name={:?}", m.name);
println!("age={:?}", m.age);
}
struct Point {
x: i32,
y: i32,
}
struct Circle {
center: Point,
radius: i32,
}
fn main(){
let c = Circle {
center: Point{x:10, y:20},
radius: 25,
};
println!("(x,y)=({}, {})", c.center.x, c.center.y);
println!("半径={}", c.radius);
}
### ジェネリック構造体
任意の型の値を扱えるようにする仕組みをジェネリックという
struct Point<T, U>{
x: T,
y: U,
}
fn main(){
let p1 = Point { x: 20, y: 10};
let p2 = Point { x: 5, y: 6.0};
println!("p1.X={}, p1.y={}",p1.x, p1.y);
println!("p2.X={}, p2.y={}",p2.x, p2.y);
}
struct Position<T, U, V>{
x: T,
y: U,
z: V,
}
fn main(){
let pos = Position { x: 5.0, y: 10, z:20.5};
println!("X={}, y={}, z={}", pos.x, pos.y, pos.z);
}
### 共用体
メンバーが同じメモリ領域を使用するデータ構造
union MyData {
va: u16,
vb: u32,
}
fn main(){
let v = MyData {vb: 0};
unsafe {
println!("v.va={}", v.va);
println!("v.vb={}", v.vb);
}
}