How to read interface value with structure address
In Go language, interface is a very powerful and flexible type. However, we may encounter some confusion when trying to read the structure address in an interface value. So, how do you read an interface value that has a struct address? In this article, we'll answer this question for you and provide some practical tips and sample code. Whether you are a beginner or an experienced Go developer, this article will help you. Let’s take a look!
Question content
I have a variable with data type interface{}
and pass it the address of the structure. Now I can't read the fields
code show as below:
type UserData struct { UserID string `json:"user_id"` UserName string `json:"user_name"` } type Result struct { Status string `json:"status"` Data interface{} `json:"data"` } var res Result res.Data = &UserData json.Unmarshal([]byte(`{"status": "success", "data": {"user_id":15,"user_name":"abc"}}`), &res) fmt.Println(res.Data) //working fine fmt.Println(res.Data.UserName) //getting error: type interface{} has no field or method UserName
If I use res.data.username
I get an error
How to read structure fields from the interface?
Workaround
Compare this with golang Why do fields that don't exist in go structs still exist after marshaling said struct to json. At first I thought they were the same. But it turned out not to be the case.
For this question, res.data
has values of type *userdata
. So a simple type assertion will do.
package main import ( "encoding/json" "fmt" ) type userdata struct { userid string `json:"user_id"` username string `json:"user_name"` } type result struct { status string `json:"status"` data interface{} `json:"data"` } func main() { var res result res.data = &userdata{} json.unmarshal([]byte(`{"status": "success", "data": {"user_id":15,"user_name":"abc"}}`), &res) fmt.println(res.data) fmt.println(res.data.(*userdata).username) }
The following demo is a merge of two demos by @mkopriva which shows the differences:
package main import ( "encoding/json" "fmt" "log" ) type dbbatch struct { fieldtokeep string `json:"field_to_keep"` fieldtokeep2 string `json:"field_to_keep2"` } func main() { jsonbatch := `{"field_to_keep":"xxxxx","field_to_keep2":"26400527","field_to_delete":"whynotdeleted"}` var i interface{} = dbbatch{} fmt.printf("%t\n", i) // type is dbbatch if err := json.unmarshal([]byte(jsonbatch), &i); err != nil { log.println(err) } fmt.printf("%t\n", i) // type is not dbbatch anymore, instead it's map[string]any i = &dbbatch{} fmt.printf("%t\n", i) // type is *dbbatch if err := json.unmarshal([]byte(jsonbatch), &i); err != nil { log.println(err) } fmt.printf("%t\n", i) // type is *dbbatch }
The output is:
main.DBBatch map[string]interface {} *main.DBBatch *main.DBBatch
The above is the detailed content of How to read interface value with structure address. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





Yes, H5 page production is an important implementation method for front-end development, involving core technologies such as HTML, CSS and JavaScript. Developers build dynamic and powerful H5 pages by cleverly combining these technologies, such as using the <canvas> tag to draw graphics or using JavaScript to control interaction behavior.

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

The method of customizing resize symbols in CSS is unified with background colors. In daily development, we often encounter situations where we need to customize user interface details, such as adjusting...

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Regarding the reasons and solutions for misaligned display of inline-block elements. When writing web page layout, we often encounter some seemingly strange display problems. Compare...

How to use JavaScript or CSS to control the top and end of the page in the browser's printing settings. In the browser's printing settings, there is an option to control whether the display is...

How to achieve the 45-degree curve effect of segmenter? In the process of implementing the segmenter, how to make the right border turn into a 45-degree curve when clicking the left button, and the point...
