Getting a string representation of a structure in Go
Go allows us to serialize data from structures using a variety of simple standard methods.
Converting a structure to a string using String method in Go
The GoLang package String helps implement simple functions to manipulate and edit UTF-8 encoded strings.
Sample code:
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!"})
}
Output:
The structure I made has the following data: Hello, World! GoLang is fun!
In the code above, we attached a String() function to a named structure called myStructure, which allows us to convert a structure into a string.
Convert structs to JSON using json.Marshal method in Go
The GoLang encoding/json package has utilities that can be used to convert to and from JSON. The json.Marshal method can convert a struct to JSON.
Sample code:
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)
}
Output:
{"From Structure":"Hello, World!"} <nil>
请注意
, when using the above method, external libraries can only use the exported fields of the defined structure. Therefore, only the exported fields of our structure will be copied into the converted JSON string.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
在 Golang 中使用 If-Else 和 Switch Loop Inside HTML 模板
Publish Date:2023/04/27 Views:104 Category:Go
-
本篇文章介绍了在 Golang 的 HTML 模板中使用 if-else 和 switch 循环。因此,只要输出是 HTML,就应该始终使用 HTML 模板包而不是文本模板。
Golang 中的零值 Nil
Publish Date:2023/04/27 Views:185 Category:Go
-
本篇文章介绍 nil 在 Golang 中的含义,nil 是 Go 编程语言中的零值,是众所周知且重要的预定义标识符。
Golang 中的 Lambda 表达式
Publish Date:2023/04/27 Views:699 Category:Go
-
本篇文章介绍如何在 Golang 中创建 lambda 表达式。Lambda 表达式似乎不存在于 Golang 中。 函数文字、lambda 函数或闭包是匿名函数的另一个名称。
在 Go 中捕获 Panics
Publish Date:2023/04/27 Views:104 Category:Go
-
像错误一样,Panic 发生在运行时。 换句话说,当您的 Go 程序中出现意外情况导致执行终止时,就会发生 Panics。让我们看一些例子来捕捉 Golang 中的Panics。
在 Go 中使用断言
Publish Date:2023/04/27 Views:593 Category:Go
-
本篇文章介绍了 assert 在 GoLang 中的使用。在 Go 语言中使用断言:GoLang 不提供对断言的任何内置支持,但我们可以使用来自 Testify API 的广泛使用的第三方包断言。
Go 中的随机数生成
Publish Date:2023/04/27 Views:207 Category:Go
-
本篇文章介绍如何在 Go 语言中使用随机数生成功能。Go 中的随机数生成 Go 语言为随机数生成功能提供内置支持。 内置包 math 有方法 rand(),用于随机数生成。
GoLang 电子邮件验证器
Publish Date:2023/04/27 Views:305 Category:Go
-
本篇文章介绍如何在 Go 语言中验证电子邮件。电子邮件需要特定格式; 否则,它们将无法工作。