Table of Contents
Question content
Workaround
Home Backend Development Golang How to read interface value with structure address

How to read interface value with structure address

Feb 10, 2024 pm 07:21 PM
go language overflow

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

from the interface

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
Copy after login

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)
}
Copy after login

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
}
Copy after login

The output is:

main.DBBatch
map[string]interface {}
*main.DBBatch
*main.DBBatch
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is H5 page production a front-end development? Is H5 page production a front-end development? Apr 05, 2025 pm 11:42 PM

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.

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

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? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

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...

How to customize the resize symbol through CSS and make it uniform with the background color? How to customize the resize symbol through CSS and make it uniform with the background color? Apr 05, 2025 pm 02:30 PM

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 provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

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, ...

Why are the inline-block elements misaligned? How to solve this problem? Why are the inline-block elements misaligned? How to solve this problem? Apr 04, 2025 pm 10:39 PM

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 control the top and end of pages in browser printing settings through JavaScript or CSS? How to control the top and end of pages in browser printing settings through JavaScript or CSS? Apr 05, 2025 pm 10:39 PM

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 use the clip-path attribute of CSS to achieve the 45-degree curve effect of segmenter? How to use the clip-path attribute of CSS to achieve the 45-degree curve effect of segmenter? Apr 04, 2025 pm 11:45 PM

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...

See all articles