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

王林
Release: 2024-02-05 11:57:54
forward
595 people have browsed it

迭代“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{}
    // ...
}
Copy after login

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

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

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

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

currentroot.components["menu"].(renderable).render()
Copy after login

To test whether something is renderable, use:

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

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!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!