Home  >  Article  >  Backend Development  >  Iterate over the map of "interface{}" and call the same method on every item in Golang

Iterate over the map of "interface{}" and call the same method on every item in Golang

王林
王林forward
2024-02-05 11:57:54553browse

迭代“interface{}”的映射并在 Golang 中的每个项目上调用相同的方法

Question content

I am developing a simple console game to learn go and got stuck on a seemingly simple problem that is not found in other languages There is no problem in Go, but it seems almost impossible in Go.

I have an interface mapped as a field in a struct like this:

type room struct {
    // ...
    components map[string]interface{}
    // ...
}

I need to iterate over the map and call the render() method for each item stored in the map (assuming they all implement the render() method. For example in js or php, This wouldn't be a problem, but I've been banging my head against the wall all day in go.

I need something like this:

for _, v := range currentroom.components {
    v.render()
}

This didn't work, but when I specified the type and manually called each item individually, it worked:

currentRoom.Components["menu"].(*List.List).Render()
currentRoom.Components["header"].(*Header.Header).Render()

How to call the render() method for each item in the map? Or if there is a better/different way to solve this problem please enlighten me as I'm at my wits' end here.


Correct answer


Define interface:

type renderable interface {
   render()
}

You can then type assertion map elements and call render as long as they implement that method:

currentroot.components["menu"].(renderable).render()

To test whether something is renderable, use:

renderable, ok:=currentRoot.Components["menu"].(Renderable)
if ok {
   renderable.Render()
}

The above is the detailed content of Iterate over the map of "interface{}" and call the same method on every item in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete