doujiena0025 2009-11-25 19:24
浏览 313

如何在Go中使用带有可为空的字符串参数的函数?

I'm used to Java's String where we can pass null rather than "" for special meanings, such as use a default value.

In Go, string is a primitive type, so I cannot pass nil (null) to a parameter that requires a string.

I could write the function using pointer type, like this:

func f(s *string)

so caller can call that function either as

f(nil)

or

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

but the following is unfortunately not allowed:

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

What is the best way to have a parameter that receives either a string or nil?

  • 写回答

4条回答 默认 最新

  • doujiurong7210 2009-11-26 10:20
    关注

    Not realy attend answer : but warping value in a structure can provide some generic utility methode. (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
    ", canBeString.String());
     } else {
      fmt.Print("Nothing to say !
    ");
     }
    }
    
    func sayMaybeNothing (canBeString maybe.AString) {
     fmt.Printf("Say : %v
    ", canBeString.OrDefault("nothing"));
    }
    
    func main() {
     aString := maybe.String("hello");
     say(aString);
     sayMaybeNothing(aString);
     noString := maybe.NoString;
     say(noString);
     sayMaybeNothing(noString);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答