Home >Backend Development >Golang >How Can I Access Struct Fields Through an Interface in Go?

How Can I Access Struct Fields Through an Interface in Go?

DDD
DDDOriginal
2024-11-29 16:27:10308browse

How Can I Access Struct Fields Through an Interface in Go?

Accessing Interface Fields in Go

When working with interfaces in Go, it's important to understand that you cannot directly access the underlying type's fields through an interface. An interface variable can store any value that conforms to the interface, but it does not provide direct access to the value's fields.

In the provided code snippet, the SearchItemsByUser function returns an interface{} value. To access the data fields, such as Params, you need to use type assertion to access the specific struct type behind the interface.

To do this, you can modify the code as follows:

package search

type results struct {
    Hits             hits
    NbHits           int
    NbPages          int
    HitsPerPage      int
    ProcessingTimeMS int
    Query            string
    Params           string
}

func SearchItemsByUser(r *http.Request) results {
    var Result results

    er := json.Unmarshal(body, &Result)
    if er != nil {
        fmt.Println("error:", er)
    }
    return Result
}

Now, you can use the returned value directly:

func test(w http.ResponseWriter, r *http.Request) {

    result := search.SearchItemsByUser(r)
    fmt.Fprintf(w, "%s", result.Params)
}

The above is the detailed content of How Can I Access Struct Fields Through an Interface in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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