0
0

More than 3 years have passed since last update.

struct内のstructを抜き出したい

Last updated at Posted at 2020-07-21

作業で使ったので、備忘録。

経緯

struct balances内のBalancesを別で定義して使いたい。


type balances struct {
    Time       int64  `json:"time"`
    Type      string `json:"type"`
    Balances         []struct {
        Asset  string `json:"asset"`
        Free   string `json:"free"`
        Locked string `json:"locked"`
    } `json:"balances"`
}

対応

結果として下記で対応を行った。


type balances struct {
    Time       int64  `json:"time"`
    Type      string `json:"type"`
    Balances         []struct {
        balance
    } `json:"balances"`
}

type balance struct {
    Asset  string `json:"asset"`
    Free   string `json:"free"`
    Locked string `json:"locked"`
}

課題

複数structの共通箇所の抜き出しに使用できるかと思うが、値を参照する際に
下記のようにstruct名の記載が増えるので、気になる。


// berore
for _, b :=  range balances.Balances {
    b.Free
}
// After
for _, b :=  range balances.Balances {
    b.balance.Free
}

以上です。
いいねやQiitaやTwitterのフォローいただけると励みになります!
他にも方法がありましたら、コメントお待ちしております。
宜しくお願いします〜

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0