首页 > 其他分享 >Go实现String方法

Go实现String方法

时间:2023-01-08 06:44:05浏览次数:45  
标签:String err struct json int64 Go 方法 string

给结构体实现String() sting方法,方便按照我们想看的方式打印出来fmt.Println(),类似与python的__str____repr__

package main_test

import (
	"fmt"
	"github.com/bytedance/sonic"
	"testing"
)

type A struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func (a A) String() string {
	s, err := sonic.MarshalString(a)
	if err != nil {
		panic(err)
	}
	return s
}
func TestAbc(t *testing.T) {
	a := &A{
		Username: "abc",
		Password: "aaa",
	}
	fmt.Println(a)
}
/*
{"username":"abc","password":"aaa"}
*/

当引用项为结构体,同时希望上层结构体直接继承下层结构体属性

例子

第一个结构体

type RequestCreateBlog struct {
	Title   string `json:"title"`
	Author  string `json:"author"`
	Summary string `json:"summary"`
	Content string `json:"content"`
	Status  int8 `json:"status"`
}

第二个结构体

type Blog struct {
	Id         int   `json:"id"`
	CreatedAt  int64 `json:"created_at"`
	UpdatedAt  int64 `json:"updated_at"`
	PulishedAt int64 `json:"pulished_at"`
	*RequestCreateBlog
}

这里的需求是,第二个结构体直接继承第一个结构体的所有属性,这里使用了指针的方式

所要达到的序列化之后的结构体是这样的:

type Blog struct {
	Id         int   `json:"id"`
	CreatedAt  int64 `json:"created_at"`
	UpdatedAt  int64 `json:"updated_at"`
	PulishedAt int64 `json:"pulished_at"`
	Title   string `json:"title"`
	Author  string `json:"author"`
	Summary string `json:"summary"`
	Content string `json:"content"`
	Status  int8 `json:"status"`
}

//而不是这样的
type Blog struct {
	Id         int   `json:"id"`
	CreatedAt  int64 `json:"created_at"`
	UpdatedAt  int64 `json:"updated_at"`
	PulishedAt int64 `json:"pulished_at"`
	RequestCreateBlog *RequestCreateBlog
}

这个时候需要实现的方法就不再是给第一个结构体实现String()

这里就是实现Blog结构体的String()方法

func (b *Blog) String() string {
	b1, err := sonic.Marshal(b)
	if err != nil {
		painc(err.Error())
	}
	return string(b1)
}

标签:String,err,struct,json,int64,Go,方法,string
From: https://www.cnblogs.com/guangdelw/p/17034049.html

相关文章