代码之家  ›  专栏  ›  技术社区  ›  Randy Sugianto 'Yuku'

如何在Go中拥有一个可以为null的字符串参数的函数?

  •  10
  • Randy Sugianto 'Yuku'  · 技术社区  · 15 年前

    使用默认值 .

    我可以使用指针类型编写函数,如下所示:

    func f(s *string)
    

    所以调用者可以调用该函数

    f(nil)
    

    // not so elegant
    temp := "hello";
    f(&temp) 
    

    但不幸的是,以下情况是不允许的:

    // elegant but disallowed
    f(&"hello");
    

    4 回复  |  直到 15 年前
        1
  •  6
  •   Billy Jo    15 年前

    我对如何使用 struct

    type MyString struct {
        val string;
    }
    
    func f(s MyString) {
        if s == nil {
            s = MyString{"some default"};
        }
        //do something with s.val
    }
    

    那你就可以打电话了 f

    f(nil);
    f(MyString{"not a default"});
    
        2
  •  5
  •   Ben Pate    9 年前

    我知道我参加这个聚会已经晚了,但我在寻找类似问题时发现了这个问题,我想我会为后人添加我的解决方案。

    根据您的用例,使用 variadic function 可能是你的朋友。这允许您向函数输入零个或多个相同类型的参数,这些参数在函数中作为数组接收。

    // My variadic function
    func f(s string...) {
      if length(s) == 0 {
        // We got a NULL
        fmt.Println("default value")
      } else {
        // We got a value
        fmt.Println(s[0])
      }
    }
    
    f() // works!
    f("has a value") // works!
    

    这个解决方案确实要求您知道在开发时将传入一个零;您不能只调用 f(nil) 让它发挥作用。但是,如果这在您的特定用例中不是问题,那么它可能是一个非常优雅的解决方案,不需要您定义任何额外的数据类型。

        3
  •  1
  •   ppierre    15 年前

    Haskell Maybe ?)

    //#maybe.go
    package maybe
    
    import "log"
    
    type MayHaveValue struct {
     IsValue bool;
    }
    
    func (this MayHaveValue) IsJust() bool {
     return this.IsValue
    }
    
    type AString struct {
     MayHaveValue;
     Value string;
    }
    
    func String(aString string) AString {
     return AString{MayHaveValue{true}, aString}
    }
    
    var NoString AString = AString{MayHaveValue{false}, ""}
    
    func (this AString) String() (value string) {
     if this.IsJust() == true {
      value = this.Value;
     } else {
      log.Crash("Access to non existent maybeString value");
     }
     return;
    }
    
    func (this AString) OrDefault(defaultString string) (value string) {
     if this.IsJust() {
      value = this.Value;
     } else {
      value = defaultString;
     }
     return;
    }
    
    //#main.go
    package main
    
    import "fmt"
    import "maybe"
    
    func say(canBeString maybe.AString) {
     if canBeString.IsJust() {
      fmt.Printf("Say : %v\n", canBeString.String());
     } else {
      fmt.Print("Nothing to say !\n");
     }
    }
    
    func sayMaybeNothing (canBeString maybe.AString) {
     fmt.Printf("Say : %v\n", canBeString.OrDefault("nothing"));
    }
    
    func main() {
     aString := maybe.String("hello");
     say(aString);
     sayMaybeNothing(aString);
     noString := maybe.NoString;
     say(noString);
     sayMaybeNothing(noString);
    }
    
        4
  •  -3
  •   RogerV    15 年前

    func f(字符串){ }其他{ } }

    要么字符串是空的,并且语义意义为younilcase,要么有一些字符串数据要处理。看不出有什么问题。