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 :-)

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

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号