如何设置限制或只注意函数参数的提示
How to set limitation or just notice hint for function's argument
如何像下面这样设置参数限制?
// 1.
func ChooseColor(color string:"black|white" ) {
fmt.Println(color)
}
ChooseColor("white") // console "white"
ChooseColor("yellow") // console panic
如果你觉得菜鸟看不懂上面的解决方案,那就交替看下面
// 2.
/**
* arg: "black|white"
*
*/
func ChooseColor(color string) {
fmt.Println(color)
}
ChooseColor( ) // IDE can notice "color: black || white"
请帮帮我(T.T)
您可以创建自己的类型 Color
并拥有该类型的常量。像这样
type Color string
const (
ColorBlack Color = "black"
ColorWhite Color = "white"
)
func ChooseColor(color Color) {
fmt.Println(color)
}
这是 1.
的解决方案。如果给定的参数不是预期的参数,函数会出现恐慌。
func ChooseColor(color string) {
switch color {
case "white", "black":
fmt.Println(color)
default:
panic(color)
}
}
而 2.
很可能由 Bakurits 回答。这让 IDE 可以捕获将传递给该函数的数据类型。
type Color bool
const (
ColorBlack Color = true
ColorWhite Color = false
)
func ChooseColor(color Color) {
if color {
fmt.Println("black")
} else {
fmt.Println("white")
}
}
执行此操作的“Go”方法是使用 godoc:
// ChooseColor selects a color. Valid colors are: black, white.
func ChooseColor(color string) {
if color != "black" && color != "white" {
/* handle the error condition */
}
/* ... */
}
这将出现在大多数 IDE 中。
如何像下面这样设置参数限制?
// 1.
func ChooseColor(color string:"black|white" ) {
fmt.Println(color)
}
ChooseColor("white") // console "white"
ChooseColor("yellow") // console panic
如果你觉得菜鸟看不懂上面的解决方案,那就交替看下面
// 2.
/**
* arg: "black|white"
*
*/
func ChooseColor(color string) {
fmt.Println(color)
}
ChooseColor( ) // IDE can notice "color: black || white"
请帮帮我(T.T)
您可以创建自己的类型 Color
并拥有该类型的常量。像这样
type Color string
const (
ColorBlack Color = "black"
ColorWhite Color = "white"
)
func ChooseColor(color Color) {
fmt.Println(color)
}
这是 1.
的解决方案。如果给定的参数不是预期的参数,函数会出现恐慌。
func ChooseColor(color string) {
switch color {
case "white", "black":
fmt.Println(color)
default:
panic(color)
}
}
而 2.
很可能由 Bakurits 回答。这让 IDE 可以捕获将传递给该函数的数据类型。
type Color bool
const (
ColorBlack Color = true
ColorWhite Color = false
)
func ChooseColor(color Color) {
if color {
fmt.Println("black")
} else {
fmt.Println("white")
}
}
执行此操作的“Go”方法是使用 godoc:
// ChooseColor selects a color. Valid colors are: black, white.
func ChooseColor(color string) {
if color != "black" && color != "white" {
/* handle the error condition */
}
/* ... */
}
这将出现在大多数 IDE 中。