Open2

TypeScript脳の人間がRustやってみて嬉しかったところ/つまづいたところ

nerikosansnerikosans

String Literal に相当する型はあるのか?

Rust の serde で外部から来たJSONをパースするとき、TSで言うところの Discriminated Union を用いた区別がしたかった

type Event = {
  type: 'text',
  content: string
} | {
  type: 'image',
  content: string
}

調べたところ

String Literal のように文字列自体を型として扱うことはしなさそう。やるならenumを定義してやるっぽい

serdeでのパースについていえば、 "Internal tag" として attribute? を設定することで対応できた:

#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
enum Event {
    #[serde(rename = "text")]
    Text(TextEvent),
}

https://serde.rs/enum-representations.html#internally-tagged

nerikosansnerikosans

structはネストして書けるのか?

TSだとこういうふうにtypeを書くことがある

type Foo = {
  foo: string,
  bar: {
    hoge: string,
  }
}

Rustでこういう感じにかけないだろうか?

struct Foo {
  foo: String,
  bar: struct {
    hoge: String,
  },
}

→ 調査中。(詳しい方ぜひ教えて下さい!)