donglu9978 2017-05-22 16:47
浏览 64
已采纳

在Go中使用Javascript在变量声明中模拟OR运算符

I want to emulate the OR | operator in Go, when I declare a variable. So return the right handside when the value is not presented:

port := strconv.Itoa(os.Getenv("PORT")) | "8080"

How can I achieve this?

  • 写回答

1条回答 默认 最新

  • dousi4472 2017-05-22 17:14
    关注

    You can't use | or || like this in Go.

    | is an Arithmetic operator and applies only to numeric values and || is a Logical operator, and applies only to boolean values.

    Go has no concept of "truthy" or "falsy" as in JavaScript; for example if "some_string" or if 0 are invalid. You'll need to explicitly use a comparison with ==, >: if 0 == 0 and if "some_string" == "".


    Itoa always returns a String, as does os.GetEnv, which is documented as returning a string and:

    It returns the value, which will be empty if the variable is not present.

    "Empty" being an "empty string". In Go, a string is always a string; only a limited set of values such as pointers and error can be compared to nil (and primitives like strings can't).

    It will never return a number type (e.g. int), so passing the output of this to Itoa is always an error.


    What you probably want is Atoi, which returns an error as the second return value:

    port, err := strconv.Atoi(os.Getenv("PORT"))
    if err != nil {
        fmt.Println("unable to get PORT environment variable, falling back to 8080")
    
        // Use =, not :=
        // Otherwise it'll create new port variable local to this if block.
        // Common mistake for beginners and even experienced programmers.
        port = 8080
    }
    

    Or:

    port := 8080
    if os.Getenv("PORT") != "" {
        var err error
        port, err = strconv.Atoi(os.Getenv("PORT"))
        if err != nil {
            fmt.Fprintf(os.Stderr, "error: unable to get PORT environment variable: %v
    ", err)
            os.Exit(1)
        }
    }
    

    If you're thinking "gee, that's verbose compared to my JavaScript one-liner!" then you're correct. In part this is due to the nature of static vs. dynamic languages, and in part this is due to Go's nature of being very explicit and easy-to-read.

    But you get type safety and readability in return :-)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改