[おまかせシリーズを理解する|ゼロベース| | rustlang言語をはじめ|(11)]

[おまかせシリーズを理解する|ゼロベース| | rustlang言語をはじめ|(11)]

興味深いことに基礎

構造体

構造体:今日はデータ構造を見てみましょう。

簡単に言えば、構造体は、データ・タイプに関連するデータをカプセル化するために使用されます。

:一般的に、構造体は、次のようなこぶ手段を命名キャメルケース

錆構造体のようにいくつかの定義があります。

  1. 構造体のようなC(C言語の構造体の形で)
  2. タプル構造体(グループの形で構造体要素)
  3. 構造体単位(構造体単位)

さび、抽象オブジェクト指向、及び一般構造体形質(機能)によって実現される、すなわち、構造体にで

属性データパッケージ、および特性のためのパッケージは、その後、独自の実装によって相関すること。

コードを見てみましょう:

Cスタイルの構造体

// Struct Declaration
struct Color {
    red: u8,
    green: u8,
    blue: u8
}

fn main() {
  // Creating an instance
  let black = Color {red: 0, green: 0, blue: 0};

  // Accessing its fields using dot notation
  println!("Black = rgb({}, {}, {})", black.red, black.green, black.blue); //Black = rgb(0, 0, 0)

  // Structs are immutable by default, use `mut` to make it mutable but doesn't support field level mutability
  let mut link_color = Color {red: 0,green: 0,blue: 255};
  link_color.blue = 238;
  println!("Link Color = rgb({}, {}, {})", link_color.red, link_color.green, link_color.blue); //Link Color = rgb(0, 0, 238)

  // Copy elements from another instance
  let blue = Color {blue: 255, .. link_color};
  println!("Blue = rgb({}, {}, {})", blue.red, blue.green, blue.blue); //Blue = rgb(0, 0, 255)

  // Destructure the instance using a `let` binding, this will not destruct blue instance
  let Color {red: r, green: g, blue: b} = blue;
  println!("Blue = rgb({}, {}, {})", r, g, b); //Blue = rgb(0, 0, 255)

  // Creating an instance via functions & accessing its fields
  let midnightblue = get_midnightblue_color();
  println!("Midnight Blue = rgb({}, {}, {})", midnightblue.red, midnightblue.green, midnightblue.blue); //Midnight Blue = rgb(25, 25, 112)

  // Destructure the instance using a `let` binding
  let Color {red: r, green: g, blue: b} = get_midnightblue_color();
  println!("Midnight Blue = rgb({}, {}, {})", r, g, b); //Midnight Blue = rgb(25, 25, 112)
}

fn get_midnightblue_color() -> Color {
    Color {red: 25, green: 25, blue: 112}
}

フォーム構造体のタプル

struct Color(u8, u8, u8);
struct Kilometers(i32);

fn main() {
  // Creating an instance
  let black = Color(0, 0, 0);

  // Destructure the instance using a `let` binding, this will not destruct black instance
  let Color(r, g, b) = black;
  println!("Black = rgb({}, {}, {})", r, g, b); //black = rgb(0, 0, 0);

  // Newtype pattern
  let distance = Kilometers(20);
  // Destructure the instance using a `let` binding
  let Kilometers(distance_in_km) = distance;
  println!("The distance: {} km", distance_in_km); //The distance: 20 km
}

構造体ユニット

struct Electron;

fn main() {
  let x = Electron;
}

上記は、私はあなたに役立つ願っています。

如果遇到什么问题,欢迎加入:rust新手群,在这里我可以提供一些简单的帮助,加微信:360369487,注明:博客园+rust

https://learning-rust.github.io/docs/b2.structs.html

おすすめ

転載: www.cnblogs.com/gyc567/p/11961235.html