package main
import (
"fmt"
"strings"
)
type MyStruct struct {
Part1 string
Part2 string
Part3 string
}
func (m *MyStruct) set(s string) *MyStruct {
p := []*string{&m.Part1, &m.Part2, &m.Part3}
for i, v := range strings.Split(s+"//", "/")[:3] {
*p[i] = v
}
return m
}
func main() {
var v MyStruct
fmt.Printf("%#v\n", v.set("foo"))
fmt.Printf("%#v\n", v.set(""))
fmt.Printf("%#v\n", v.set("bar/baz"))
fmt.Printf("%#v\n", v.set("alpha//omega"))
fmt.Printf("%#v\n", v.set("/var/mail"))
}
操场
输出:
&main.MyStruct{Part1:"foo", Part2:"", Part3:""}
&main.MyStruct{Part1:"", Part2:"", Part3:""}
&main.MyStruct{Part1:"bar", Part2:"baz", Part3:""}
&main.MyStruct{Part1:"alpha", Part2:"", Part3:"omega"}
&main.MyStruct{Part1:"", Part2:"var", Part3:"mail"}