And*_*are 391
Go没有可选参数,也不支持方法重载:
如果不需要进行类型匹配,则简化方法调度.使用其他语言的经验告诉我们,使用具有相同名称但签名不同的各种方法偶尔会有用,但在实践中它也可能令人困惑和脆弱.仅根据名称进行匹配并要求在类型中保持一致性是Go类型系统中的主要简化决策.
Fer*_*uzz 193
实现类似可选参数的好方法是使用可变参数args.该函数实际上接收您指定的任何类型的切片.
func foo(params ...int) {
fmt.Println(len(params))
}
func main() {
foo()
foo(1)
foo(1,2,3)
}
Run Code Online (Sandbox Code Playgroud)
dea*_*mon 153
您可以使用包含参数的结构:
type Params struct {
a, b, c int
}
func doIt(p Params) int {
return p.a + p.b + p.c
}
// you can call it without specifying all parameters
doIt(Params{a: 1, c: 9})
Run Code Online (Sandbox Code Playgroud)
Del*_*ace 106
对于任意的,可能大量的可选参数,一个很好的习惯是使用功能选项.
对于您的类型Foobar,首先只写一个构造函数:
func NewFoobar(options ...func(*Foobar) error) (*Foobar, error){
fb := &Foobar{}
// ... (write initializations with default values)...
for _, op := range options{
err := op(fb)
if err != nil {
return nil, err
}
}
return fb, nil
}
Run Code Online (Sandbox Code Playgroud)
其中每个选项都是一个改变Foobar的函数.然后为用户提供方便的方式来使用或创建标准选项,例如:
func OptionReadonlyFlag(fb *Foobar) error {
fb.mutable = false
return nil
}
func OptionTemperature(t Celsius) func(*Foobar) error {
return func(fb *Foobar) error {
fb.temperature = t
return nil
}
}
Run Code Online (Sandbox Code Playgroud)
为简明起见,您可以为选项类型(Playground)命名:
type OptionFoobar func(*Foobar) error
Run Code Online (Sandbox Code Playgroud)
如果需要必需参数,请在变量数据之前将它们添加为构造函数的第一个参数options.
功能选项习惯用语的主要好处是:
这种技术是由Rob Pike创造的,Dave Cheney也证明了这一点.
所以我觉得我参加这个聚会已经太晚了,但我一直在寻找是否有比我已经做的更好的方法。这有点解决了您想要做的事情,同时也给出了可选参数的概念。
package main
import "fmt"
type FooOpts struct {
// optional arguments
Value string
}
func NewFoo(mandatory string) {
NewFooWithOpts(mandatory, &FooOpts{})
}
func NewFooWithOpts(mandatory string, opts *FooOpts) {
if (&opts) != nil {
fmt.Println("Hello " + opts.Value)
} else {
fmt.Println("Hello")
}
}
func main() {
NewFoo("make it work please")
NewFooWithOpts("Make it work please", &FooOpts{Value: " World"})
}
Run Code Online (Sandbox Code Playgroud)
更新1:
添加了一个功能示例来展示功能与示例
您可以使用地图传递任意命名参数。aType = map[key].(*foo.type)如果参数具有非统一类型,则必须使用“ ”来断言类型。
type varArgs map[string]interface{}
func myFunc(args varArgs) {
arg1 := "default"
if val, ok := args["arg1"]; ok {
arg1 = val.(string)
}
arg2 := 123
if val, ok := args["arg2"]; ok {
arg2 = val.(int)
}
fmt.Println(arg1, arg2)
}
func Test_test() {
myFunc(varArgs{"arg1": "value", "arg2": 1234})
}
Run Code Online (Sandbox Code Playgroud)
Go 不支持可选参数、默认值和函数重载,但您可以使用一些技巧来实现相同的功能。
\n分享一个示例,您可以在一个函数中使用不同数量和类型的参数。它\xe2\x80\x99是一个简单的代码,为了便于理解,您需要添加错误处理和一些逻辑。
\nfunc student(StudentDetails ...interface{}) (name string, age int, area string) {\n age = 10 //Here Age and area are optional params set to default values\n area = "HillView Singapore"\n\n for index, val := range StudentDetails {\n switch index {\n case 0: //the first mandatory param\n name, _ = val.(string)\n case 1: // age is optional param\n age, _ = val.(int)\n case 2: //area is optional param\n area, _ = val.(string)\n }\n }\n return\n}\n\nfunc main() {\n fmt.Println(student("Aayansh"))\n fmt.Println(student("Aayansh", 11))\n fmt.Println(student("Aayansh", 15, "Bukit Gombak, Singapore"))\n}\nRun Code Online (Sandbox Code Playgroud)\n
如果您不想使用指针,则可以使用指针并将它们保留为零:
func getPosts(limit *int) {
if optParam != nil {
// fetch posts with limit
} else {
// fetch all posts
}
}
func main() {
// get Posts, limit by 2
limit := 2
getPosts(&limit)
// get all posts
getPosts(nil)
}
Run Code Online (Sandbox Code Playgroud)
不-都不。根据Go for C ++程序员文档,
Go不支持函数重载,也不支持用户定义的运算符。
我找不到一个同样明确的说法,即不支持可选参数,但也不支持它们。
您可以将其很好地封装在类似于以下内容的 func 中。
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
fmt.Println(prompt())
}
func prompt(params ...string) string {
prompt := ": "
if len(params) > 0 {
prompt = params[0]
}
reader := bufio.NewReader(os.Stdin)
fmt.Print(prompt)
text, _ := reader.ReadString('\n')
return text
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,提示默认有一个冒号,前面有一个空格。. .
:
Run Code Online (Sandbox Code Playgroud)
. . . 但是,您可以通过向提示函数提供参数来覆盖它。
prompt("Input here -> ")
Run Code Online (Sandbox Code Playgroud)
这将导致如下提示。
Input here ->
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
205256 次 |
| 最近记录: |