いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Goメモ-267 (TOMLファイルを書き出し)(toml, Marshal)

概要

以下、自分用のメモです。

以前にファイルI/O周りについては、以下の記事を書いていました。

devlights.hatenablog.com

TOMLファイルを読み書きする必要がありましたので、勿体ないのでここにメモメモ。。。

TOMLファイルについては、以下の情報を見ると大体わかります。Python界隈ではおなじみですね。

ja.wikipedia.org

github.com

今回は Marshal してみます。Unmarshal については、一つ前の記事でサンプル書いていますので、よろしければそちらご参照ください。

GoでTOMLファイルを扱う場合は以下のライブラリが有名みたいなので、それを使っています。

github.com

ライブラリ取得

v2 が出ているので、v2側を go get します。

$ go get github.com/pelletier/go-toml/v2
go: downloading github.com/pelletier/go-toml/v2 v2.0.5
go: downloading github.com/pelletier/go-toml v1.9.5
go: added github.com/pelletier/go-toml/v2 v2.0.5

サンプル

package tomlop

import (
    "github.com/devlights/gomy/output"
    "github.com/pelletier/go-toml/v2"
)

// Marshal は、TOMLファイルの内容を書き込むサンプルです.
//
// # REFERENCES
//   - https://www.meetgor.com/golang-config-file-read/
//   - https://github.com/pelletier/go-toml
//   - https://ja.wikipedia.org/wiki/TOML
func Marshal() error {
    type (
        ValuesSection struct {
            Value1 int      `toml:"value1"` // 数値
            Value2 string   `toml:"value2"` // 文字列
            Value3 bool     `toml:"value3"` // ブール
            Value4 []string `toml:"value4"` // リスト
        }

        AuthorSection struct {
            Name string // タグ指定なし
        }

        Person struct {
            Name string `toml:"name"`
            Age  int    `toml:"age,omitempty"`
        }

        Root struct {
            Values  ValuesSection
            Author  AuthorSection
            Persons []Person
        }
    )

    var (
        valuesSection = ValuesSection{
            Value1: 999,
            Value2: "hello世界",
            Value3: false,
            Value4: []string{"Go", "C#", "Python"},
        }
        authorSection = AuthorSection{
            Name: "devlights",
        }
        persons = []Person{
            {Name: "one", Age: 30},
            {Name: "two"},
            {Name: "three", Age: 99},
        }
        root = Root{
            Values:  valuesSection,
            Author:  authorSection,
            Persons: persons,
        }
    )

    var (
        serialized []byte
        err        error
    )

    serialized, err = toml.Marshal(&root)
    if err != nil {
        return err
    }

    output.Stdoutf("[Marshal]", "\n%s\n", string(serialized))

    return nil
}

実行すると以下のようになります。

$ task run
task: [run] go run . -onetime

ENTER EXAMPLE NAME: toml_marshal

[Name] "toml_marshal"
[Marshal]            
[Values]
value1 = 999
value2 = 'hello世界'
value3 = false
value4 = ['Go', 'C#', 'Python']

[Author]
Name = 'devlights'

[[Persons]]
name = 'one'
age = 30

[[Persons]]
name = 'two'

[[Persons]]
name = 'three'
age = 99



[Elapsed] 77.02µs

参考情報

try-golang/examples/basic/tomlop at master · devlights/try-golang · GitHub

Go言語による並行処理

Go言語による並行処理

Amazon


過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。