Let's say I have array with integer
and nil
elements:
[15698, nil, 13000, 560365, nil]
I want to convert this array to string where each element separated by ,
.
[15698, null, 13000, 560365, null]
I tried next code but it return 0 instead of null. How to fix it?
func ConvertIntArrayToString(input []int) string {
if len(input) == 0 {
return ""
}
estimate := len(input) * 4
b := make([]byte, 0, estimate)
for _, n := range input {
b = strconv.AppendInt(b, int64(n), 10)
b = append(b, ',')
}
b = b[:len(b)-1]
return string(b)
}
Here is how I created array:
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}
}
var x = []utils.NilInt{utils.NewNil(), utils.NewInt(10), utils.NewNil(), utils.NewInt(5)}]
var result strings.Builder
for _, n := range x {
if n.Value() == nil {
result.WriteString("null,")
} else {
result.WriteString(??? + ",")
}
}
fmt.Println(result)