@kyanny's blog

My thoughts, my life. Views/opinions are my own.

Go: struct リテラルを返す関数

戻り値の型も同じものを書けば(冗長だが)いける。

package main

import "fmt"

func f() struct{Msg string} {
    return struct{
        Msg string
    }{
        Msg: "Yo",
    }
}

func g() *struct{Msg string} {
    return &struct{
        Msg string
    }{
        Msg: "Go",
    }
}

func main() {
    fmt.Printf("%#v\n", f().Msg)
    fmt.Printf("%#v\n", g().Msg)
}

実験結果

https://play.golang.org/p/Kq6-RJp-VZd