GoLang 打印结构中变量的值

我不是 GoLang 专家,但我需要对项目进行故障排除。现在我尝试打印相同变量的值,但我收到的输出是地址而不是值:


attrs := core.Attributes{}

    err = rtrV1.SetAttributesStruct(&attrs, sessAttrs, session.NasIP, ipv4Session, ipv6Session)

    if err1, ok := err.(core.SessionNotFoundError); ok {

        apiH.Logger.Info(err1.Error())

        c.JSON(404, gin.H{"message": err.Error()})

        return

    } else if err != nil {

        apiH.Logger.Error(err.Error())

        c.JSON(500, gin.H{"message": "internal error"})

        return

    }


    err = core.MakeNASProxyRequest(apiH.HttpClient, nasproxyHost, nasproxyPort, authToken, attrs)


    debugAttrs := fmt.Sprintf("%+p", attrs)

    debugAttrs2 := fmt.Sprintf("%+v", attrs)    

    apiH.Logger.Info("attrs:"+" "+debugAttrs, log.Field("type", "serve-request"))

    apiH.Logger.Info("attr2:"+" "+debugAttrs2, log.Field("type", "serve-request"))

我需要打印attrs,但我收到了这个输出:


"msg":"attrs: %!p(core.Attributes={+0xc000420460 <nil> <nil> +0xc000238c60 <nil> <nil> <nil> <nil> +0xc000238c98 <nil> <nil> <nil> <nil>})"

"msg":"attr2: {NASIPAddress:0xc000420460 NASIdentifier:<nil> NASIPv6Address:<nil> Username:0xc000238c60 NASPort:<nil> FramedIPAddress:<nil> CalledStationID:<nil> CallingStationID:<nil> AcctSessionID:0xc000238c98 AcctMultiSessionID:<nil> NASPortID:<nil> FramedInterfaceID:<nil> FramedIPv6Prefix:<nil>}"

如何打印值?谢谢您的帮助


慕村225694
浏览 95回答 2
2回答

LEATH

您可以使用fmt包或 JSON 编组来打印结构值...例如import "fmt"type Person struct {&nbsp; &nbsp; FirstName string}func main() {&nbsp; &nbsp; p := &Person{"mr1"}&nbsp; &nbsp; fmt.Printf("%+v", p)}或者import (&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "fmt")type Person struct {&nbsp; &nbsp; FirstName string}func main() {&nbsp; &nbsp; p := &Person{"mr1"}&nbsp; &nbsp; s, _ := json.Marshal(p)&nbsp; &nbsp; fmt.Printf("%s\n", s)}

慕工程0101907

你可以使用深漂亮的打印机。进口:github.com/davecgh/go-spew/spew例子:spew.Dump(attrs)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go