program story

Go 방법의 기본값

inputbox 2020. 12. 15. 19:17
반응형

Go 방법의 기본값


Go의 기능에 기본값을 지정하는 방법이 있습니까? 나는 이것을 문서에서 찾으려고 노력하고 있지만 이것이 가능하다는 것을 지정하는 것을 찾을 수 없습니다.

func SaySomething(i string = "Hello")(string){
...
}

아니요, Google의 권한은이를 지원하지 않기로 결정했습니다.

https://groups.google.com/forum/#!topic/golang-nuts/-5MCaivW0qQ


아니요,하지만 기본값을 구현하는 다른 옵션이 있습니다. 이 몇 가지 좋은 블로그 게시물 몇 가지 구체적인 예는 여기에있는 주제에,하지만.


옵션 1 : 호출자가 기본값을 사용하도록 선택

// Both parameters are optional, use empty string for default value
func Concat1(a string, b int) string {
  if a == "" {
    a = "default-a"
  }
  if b == 0 {
    b = 5
  }

  return fmt.Sprintf("%s%d", a, b)
}


옵션 2 : 끝에 단일 선택적 매개 변수

// a is required, b is optional.
// Only the first value in b_optional will be used.
func Concat2(a string, b_optional ...int) string {
  b := 5
  if len(b_optional) > 0 {
    b = b_optional[0]
  }

  return fmt.Sprintf("%s%d", a, b)
}


옵션 3 : 구성 구조체

// A declarative default value syntax
// Empty values will be replaced with defaults
type Parameters struct {
  A string `default:"default-a"` // this only works with strings
  B string // default is 5
}

func Concat3(prm Parameters) string {
  typ := reflect.TypeOf(prm)

  if prm.A == "" {
    f, _ := typ.FieldByName("A")
    prm.A = f.Tag.Get("default")
  }

  if prm.B == 0 {
    prm.B = 5
  }

  return fmt.Sprintf("%s%d", prm.A, prm.B)
}


옵션 4 : 전체 가변 인수 구문 분석 (자바 스크립트 스타일)

func Concat4(args ...interface{}) string {
  a := "default-a"
  b := 5

  for _, arg := range args {
    switch t := arg.(type) {
      case string:
        a = t
      case int:
        b = t
      default:
        panic("Unknown argument")
    }
  }

  return fmt.Sprintf("%s%d", a, b)
}

No, there is no way to specify defaults. I believer this is done on purpose to enhance readability, at the cost of a little more time (and, hopefully, thought) on the writer's end.

I think the proper approach to having a "default" is to have a new function which supplies that default to the more generic function. Having this, your code becomes clearer on your intent. For example:

func SaySomething(say string) {
    // All the complicated bits involved in saying something
}

func SayHello() {
    SaySomething("Hello")
}

With very little effort, I made a function that does a common thing and reused the generic function. You can see this in many libraries, fmt.Println for example just adds a newline to what fmt.Print would otherwise do. When reading someone's code, however, it is clear what they intend to do by the function they call. With default values, I won't know what is supposed to be happening without also going to the function to reference what the default value actually is.

ReferenceURL : https://stackoverflow.com/questions/19612449/default-value-in-gos-method

반응형