package syncutils import ( "fmt" "strconv" "testing" ) func TestSyncVar(t *testing.T) { syncSlice := NewSyncVar([]string{"aaa", "bbb", "ccc"}, false) syncSlice.ForWrite(func(s []string) []string { return append(s, "ddd") }) syncSlice.ForRead(func(s []string) { for i, v := range s { fmt.Println("Index", strconv.Itoa(i)+":", v) } fmt.Println() }) syncSlice.ForWrite(func(s []string) []string { for i, v := range s { if v == "ddd" { return append(s[:i], s[i+1:]...) } } return s }) syncSlice.ForRead(func(s []string) { for i, v := range s { fmt.Println("Index", strconv.Itoa(i)+":", v) } fmt.Println() }) rwSyncSlice := NewSyncVar([]string{"aaa", "bbb", "ccc"}, true) rwSyncSlice.ForWrite(func(s []string) []string { return append(s, "ddd") }) rwSyncSlice.ForRead(func(s []string) { for i, v := range s { fmt.Println("Index", strconv.Itoa(i)+":", v) } fmt.Println() }) rwSyncSlice.ForWrite(func(s []string) []string { for i, v := range s { if v == "ddd" { return append(s[:i], s[i+1:]...) } } return s }) rwSyncSlice.ForRead(func(s []string) { for i, v := range s { fmt.Println("Index", strconv.Itoa(i)+":", v) } fmt.Println() }) type Student struct { Name string Age int } rwSyncStruct := NewSyncVar(&Student{ Name: "test", Age: 10, }, true) rwSyncStruct.ForRead(func(v *Student) { fmt.Println("Name:", v.Name) fmt.Println("Age:", v.Age) fmt.Println() }) rwSyncStruct.ForWrite(func(v *Student) *Student { v.Name = "test_new" v.Age = 20 return v }) rwSyncStruct.ForRead(func(v *Student) { fmt.Println("Name:", v.Name) fmt.Println("Age:", v.Age) fmt.Println() }) }