面试题答案
一键面试- 定义自定义类型:
首先定义一个包含多个字符串的切片类型,并实现
flag.Value
接口,该接口有String
和Set
方法。package main import ( "flag" "fmt" "strings" ) type customSlice []string func (cs *customSlice) String() string { return fmt.Sprintf("%v", *cs) } func (cs *customSlice) Set(value string) error { parts := strings.Split(value, ",") for _, part := range parts { *cs = append(*cs, part) } return nil }
- 在主函数中使用自定义类型标志:
在
main
函数中定义并解析命令行标志。func main() { var myCustomSlice customSlice flag.Var(&myCustomSlice, "myflag", "A custom flag of type customSlice") flag.Parse() fmt.Println("Parsed custom slice:", myCustomSlice) }
- 错误处理:
在
Set
方法中进行错误处理。例如,如果输入格式不符合预期,可以返回一个错误。修改Set
方法如下:
在func (cs *customSlice) Set(value string) error { if value == "" { return fmt.Errorf("value cannot be empty") } parts := strings.Split(value, ",") for _, part := range parts { if part == "" { return fmt.Errorf("invalid part in value: %s", value) } *cs = append(*cs, part) } return nil }
main
函数中可以通过flag.Parse()
的返回值来处理错误。例如:func main() { var myCustomSlice customSlice flag.Var(&myCustomSlice, "myflag", "A custom flag of type customSlice") if err := flag.Parse(); err != nil { fmt.Println("Error parsing flag:", err) return } fmt.Println("Parsed custom slice:", myCustomSlice) }
实现步骤总结:
- 定义自定义类型并实现
flag.Value
接口的String
和Set
方法。 - 在
main
函数中使用flag.Var
来注册自定义类型的标志。 - 使用
flag.Parse
来解析命令行标志,并在Set
方法和flag.Parse
调用处处理可能出现的错误。