相关疑难解决方法(0)

可选参数?

Can Go有可选参数吗?或者我可以只定义两个具有相同名称和不同数量的参数的函数?

overloading go

411
推荐指数
11
解决办法
21万
查看次数

Go struct 构造函数中具有默认值的可选参数

我发现自己使用以下模式作为在 Go 结构构造函数中使用默认值获取可选参数的方法:

package main

import (
    "fmt"
)

type Object struct {
    Type int
    Name string
}

func NewObject(obj *Object) *Object {
    if obj == nil {
        obj = &Object{}
    }
    // Type has a default of 1
    if obj.Type == 0 {
        obj.Type = 1
    }
    return obj
}

func main() {
    // create object with Name="foo" and Type=1
    obj1 := NewObject(&Object{Name: "foo"})
    fmt.Println(obj1)

    // create object with Name="" and Type=1
    obj2 := NewObject(nil)
    fmt.Println(obj2)

    // create object …
Run Code Online (Sandbox Code Playgroud)

constructor default go

5
推荐指数
2
解决办法
1万
查看次数

标签 统计

go ×2

constructor ×1

default ×1

overloading ×1