First a bit of theory. Python is a dynamically typed language. While each individual value has a type, your variables can be assigned values of any type without a problem. As a consequence, python collections can contain multiple types of values and don't complain. The following is a valid python tuple (1, 'a', None, True)
. Go is a statically typed language. If your variable is defined as an integer you cannot assign any non-integer value to it. As a consequence, collections in Go have a type and can only contain a single type of object.
Now to practice. There are a few ways to do what you want. The classical C way would be to pick an integer value you are never going to encounter and use that as a null value. A 0 or a -1 or something. This is not very robust though.
A more idiomatic way is to define your own type.
package main
import "fmt"
type NilInt struct {
value int
null bool
}
func (n *NilInt) Value() interface{} {
if n.null {
return nil
}
return n.value
}
func NewInt(x int) NilInt {
return NilInt{x, false}
}
func NewNil() NilInt {
return NilInt{0, true}
}
func main() {
var x = []NilInt{NewNil(), NewInt(10), NewNil(), NewInt(5)}
for _, i := range x {
fmt.Printf("%v ", i.Value())
}
}