Go で構造体の文字列表現を取得する
    
    Musfirah Waseem
    2023年6月20日
    
    Go
    Go Struct
    
 
Go では、構造体からデータをシリアル化するための複数の単純な標準的な方法を使用できます。
Go で String メソッドを使用して構造体を文字列に変換する
    
GoLang パッケージ String は、UTF-8 でエンコードされた文字列 を操作および編集するための単純な関数を実装するのに役立ちます。
コード例:
package main
import "fmt"
type myStructure struct {
    bar string
}
func (f myStructure) String() string {
    return fmt.Sprintf("The structure I made has the following data: %s", f.bar)
}
func main() {
    fmt.Println(myStructure{"Hello, World! GoLang is fun!"})
}
出力:
The structure I made has the following data: Hello, World! GoLang is fun!
上記のコードでは、myStructure という名前の構造体に String() 関数をアタッチして、構造体を文字列に変換できるようにしています。
json.Marshal メソッドを使用して Go で構造体を JSON に変換する
GoLang encoding/json パッケージには、JSON との変換に使用できるユーティリティがあります。 json.Marshal メソッドは、構造体を JSON に変換できます。
コード例:
package main
import (
	"encoding/json"
	"fmt"
)
func main() {
	type MyStructure struct {
		Message string `json:"From Structure"`
	}
	val := &MyStructure{
		Message: "Hello, World!",
	}
	// convert struct to json string
	jsonBytes, err := json.Marshal(val)
	fmt.Println(string(jsonBytes), err)
}
出力:
{"From Structure":"Hello, World!"} <nil>
上記の方法を使用している間は、定義された構造体のエクスポートされたフィールドのみが外部ライブラリで使用できることに注意してください。 したがって、構造体のエクスポート フィールドのみが、変換された JSON 文字列にコピーされます。
        チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe
    
著者: Musfirah Waseem
    Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.
LinkedIn