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