切片
数组转字符串
package main
import (
"fmt"
"strings"
)
func main() {
arr := []string{"apple", "banana", "orange"}
str := strings.Join(arr, ", ")
fmt.Println(str)
}
数组变为 null
package script
import (
"encoding/json"
"fmt"
"testing"
)
type Ints []int
func (i Ints) MarshalJSON() ([]byte, error) {
if len(i) == 0 {
return json.Marshal([]interface{}{})
} else {
var tempValue []interface{} // 这里需要重新定义一个变量,再序列化,否则会造成循环调用
for _, item := range i {
tempValue = append(tempValue, item)
}
return json.Marshal(tempValue)
}
}
type TestStruct struct {
Ids []int
Id1 Ints
Ids2 Ints
}
func Test(t *testing.T) {
ids2 := []int{1, 2, 3, 4}
testStruct := TestStruct{}
testStruct.Ids2 = ids2 //不需要将ids2定义成Ints,用原有的类型就可以了
marshal, _ := json.Marshal(testStruct)
fmt.Println(string(marshal))
}