Rust構造体

異なる型の値を決まった構造で管理する
struct 構造体名{
フィールド名: 型,
フィールド名: 型,

}

struct Person {
	name: String,
	mail: String,
	age: i32
}

fn print_person(p:Person) {
	println!("I'm {}({}). Mail to {}.", p.name, p.age, p.mail);
}

fn main(){
	let taro = Person {
		name:String::from("Taro"),
		mail:String::from("taro@yamada"),
		age: 39
	};
	let hanako = Person {
		name:String::from("Hanako"),
		mail:String::from("hanako@flower"),
		age: 28
	};
	print_person(taro);
	print_person(hanako);

}

### タプル構造体
構造体名の後にタプル()で記述する

struct Person (String, String, i32);

fn print_person(p:Person) {
	println!("I'm {}({}). Mail to {}.", p.0, p.2, p.1);
}

fn main(){
	let taro = Person (
		String::from("Taro"),
		String::from("taro@yamada"),
		39
	);
	let hanako = Person (
		String::from("Hanako"),
		String::from("hanako@flower"),
		28
	);
	print_person(taro);
	print_person(hanako);
}

構造体は値を保管するためのもの
implというブロックを使う

出力メソッドを実装

struct Person {
	name: String,
	mail: String,
	age: i32
}

fn person(name:String, mail:String, age)-> Person {
	Person {name, mail, age}
}

impl Person {
	fn print(&self) {
		println!("{}<{}>({}).", self.name, self.mail, self.age);
	}
}

fn main(){
	let taro = person {
		String::from("Taro"),

selfのない関数

struct Person {
	name: String,
	mail: String,
	age: i32
}

fn person(name:String, mail:String, age:i32)-> Person {
	Person {name, mail, age}
}

impl Person {
	fn print(&self) {
		println!("{}<{}>({}).", self.name, self.mail, self.age);
	}
	fn fields()->[String;3] {
		[
			String::from("name:String"),
			String::from("mail:String"),
			String::from("age:i32"),
		]
	}
}

fn main(){
	let taro = person {
		String::from("Taro"),
		String::from("taro@yamada"),
		39
	};
	let hanako = person {
		String::from("Hanako"),
		String::from("hanako@flower"),
		28
	};
	taro.print();
	hanako.print();
	println!("Person's fields: {:?}", Person::fields());
}