How to achieve something like a list of void * (or variant) in Go?

I'm a Go beginner who has been studying Golang for about 3 days (although it's still new). Lua allowed you to add different types of data to a table, but what about Go? After studying Go, I did some research, but I couldn't find the answer, so I'll write it here.

Variant type in Go

After a lot of research, it seems that the Variant type in Go should be interface {}. I am grateful to the page "Learning in a hurry Go lang # 6 interface" that explains in a very easy-to-understand manner.

so,

variant.go


var s interface{}
s=1.23
fmt.Printf("s=%f\n",s.(float64))
s="hello"
fmt.Printf("s=%s\n",s.(string))

And when you execute it,

resut-variant.txt


s=1.230000
s=hello

And you can confirm that you can certainly substitute anything.

List of Variants in Go

In Go, variable length arrays are called slices. When any type is represented by the letter T, the slice type of T is [] T. So, it seems that the slice type that can store any type should be written as var list \ [] interface \ {}. In fact, it seems to be working.

variant-slice.go


var list []interface{}
list=append(list,10)
fmt.Printf("list[0]=%d\n",list[0].(int))

Advanced: Create a stack that can push and pop anything

That's why it's an advanced version. Define a Stack type and try to push and pop data of various types.

First is the definition of the stack. Pop returns two values, with the second return value indicating whether it was successfully popped (= true) or popped when the stack was empty (= false).

stack.go


package main

type Stack struct {
    index int
    dataBody []interface{}
}

func (self *Stack) Push(inData interface{}) {
    self.index++
    self.dataBody=append(self.dataBody,inData)
}

func (self *Stack) Pop() (interface{},bool) {
    if self.index<=0 {
        return nil,false
    }
    var ret interface{}
    ret,self.dataBody=self.dataBody[len(self.dataBody)-1],
                      self.dataBody[:len(self.dataBody)-1]
    self.index--
    return ret,true
}

For the Pop from the slice, I referred to the Pop from "SliceTricks" (or rather, it's the same ...).

Next is the test program.

test-stack.go


package main

import "fmt"

var DS Stack

func main() {
    DS.Push(10)
    DS.Push("aaa")
    t,_:=DS.Pop()
    fmt.Printf("%s\n",t.(string))
    t,_=DS.Pop()
    fmt.Printf("%d\n",t.(int))
    t,ok:=DS.Pop()
    if ok {
        fmt.Println("OK")
    } else {
        fmt.Println("Data stack is empty")
    }
}

When I run it,

result-test-stack.txt


aaa
10
Data stack is empty

Shows that integers and strings can be pushed and popped onto the same stack.

Summary

We found that Variant types in go can be achieved by utilizing an empty interface, and that slices can also be achieved by writing them normally. If you want to share one stack with multithreading or goroutine, you may need to lock / unlock with mutex, but common sense in C or C # may not work, so that's about it. I would like to study a lot about it.

Recommended Posts

How to achieve something like a list of void * (or variant) in Go?
How to format a list of dictionaries (or instances) well in Python
How to get a list of built-in exceptions in python
[Python] How to put any number of standard inputs in a list
How to clear tuples in a list (Python)
[Go] How to write or call a function
How to pass the execution result of a shell command in a list in Python
How to get a list of files in the same directory with python
How to write a list / dictionary type of Python3
How to identify the element with the smallest number of characters in a Python list?
How to check in Python if one of the elements of a list is in another list
[Python] How to make a list of character strings character by character
How to shuffle a part of a Python list (at random.shuffle)
How to import a file anywhere you like in Python
How to develop in a virtual environment of Python [Memo]
How to display a list of installable versions with pyenv
How to get the last (last) value in a list in Python
How to get a list of links from a page from wikipedia
How to get a quadratic array of squares in a spiral!
How to connect the contents of a list into a string
[Python] How to delete rows and columns in a table (list of drop method options)
When I got a list of study sessions in Python, I found something I wanted to make
How to pass the execution result of a shell command in a list in Python (non-blocking version)
How to display a specified column of files in Linux (awk)
How to determine the existence of a selenium element in Python
[Python] How to force a method of a subclass to do something specific
How to compare lists and retrieve common elements in a list
Try to get a list of breaking news threads in Python.
How to make a string into an array or an array into a string in Python
How to check the memory size of a variable in Python
How to check the memory size of a dictionary in Python
How to get the vertex coordinates of a feature in ArcPy
How to create a large amount of test data in MySQL? ??
Create a function to get the contents of the database in Go
How to delete multiple specified positions (indexes) in a Python list
[Python] How to convert a 2D list to a 1D list
Display a list of alphabets in Python 3
How to send a visualization image of data created in Python to Typetalk
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[Linux] Command to get a list of commands executed in the past
How to get a stacktrace in python
I want to sort a list in the order of other lists
Summary of how to use Python list
How to make a request to bitFlyer Lightning's Private API in Go language
How to mention a user group in slack notification, how to check the id of the user group
How to count the number of elements in Django and output to a template
Convert PDF of list of Go To EAT member stores in Niigata prefecture to CSV
A memorandum of how to execute the! Sudo magic command in Jupyter Notebook
I want to see a list of WebDAV files in the Requests module
What do you like about how to convert an array (list) to a string?
A simple example of how to use ArgumentParser
How to keep track of work in Powershell
How to embed a variable in a python string
Summary of how to import files in Python 3
How to create a JSON file in Python
Make a copy of the list in Python
Summary of how to use MNIST in Python
How to implement a gradient picker in Houdini
How to notify a Discord channel in Python
[Python] How to draw a histogram in Matplotlib
How to create a Rest Api in Django