Emulate OR operator in variable declaration from Javascript in Go

huangapple go评论76阅读模式
英文:

Emulate OR operator in variable declaration from Javascript in Go

问题

你可以使用条件语句来实现在变量声明时模拟OR |运算符的效果。在Go语言中,可以使用短路逻辑运算符||来实现这个目的。下面是一个示例代码:

port := os.Getenv("PORT")
if port == "" {
    port = "8080"
}

这段代码首先尝试获取环境变量"PORT"的值赋给port变量,如果获取的值为空字符串,则将port变量赋值为"8080"。这样就实现了当值不存在时返回右侧的效果。

英文:

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:

<!-- language: lang-golang -->

port := strconv.Itoa(os.Getenv(&quot;PORT&quot;)) | &quot;8080&quot;

How can I achieve this?

答案1

得分: 1

在Go语言中,不能像这样使用|||

|是一个算术运算符,只适用于数值类型,而||是一个逻辑运算符,只适用于布尔类型。

Go语言没有像JavaScript中的"truthy"或"falsy"的概念;例如if "some_string"if 0是无效的。你需要明确地使用==>等比较运算符,例如if 0 == 0if "some_string" == ""


Itoa总是返回一个字符串,os.GetEnv也是返回一个字符串,并且文档中说明:

> 它返回该变量的值,如果变量不存在则返回空字符串。

"Empty"表示"空字符串"。在Go语言中,字符串始终是字符串;只有一些有限的值,如指针和error,可以与nil进行比较(而基本类型如字符串则不能)。

它永远不会返回数值类型(如int),所以将其输出传递给Itoa总是错误的。


你可能想要使用的是Atoi,它会返回一个错误作为第二个返回值:

port, err := strconv.Atoi(os.Getenv("PORT"))
if err != nil {
    fmt.Println("无法获取PORT环境变量,回退到8080")

    // 使用=,而不是:=
    // 否则它会创建一个局部于该if块的新port变量。
    // 这是初学者甚至有经验的程序员常犯的错误。
    port = 8080
}

或者:

port := 8080
if os.Getenv("PORT") != "" {
    var err error
    port, err = strconv.Atoi(os.Getenv("PORT"))
	if err != nil {
		fmt.Fprintf(os.Stderr, "错误:无法获取PORT环境变量:%v\n", err)
		os.Exit(1)
	}
}

如果你在想"哇,相比我的JavaScript一行代码,这太冗长了!",那么你是正确的。部分原因是静态语言与动态语言的性质不同,部分原因是Go语言非常明确和易读的特性。

但是你会得到类型安全和可读性作为回报 Emulate OR operator in variable declaration from Javascript in Go

英文:

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 &quot;some_string&quot; or if 0 are invalid. You'll need to explicitly use a comparison with ==, &gt;: if 0 == 0 and if &quot;some_string&quot; == &quot;&quot;.


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(&quot;PORT&quot;))
if err != nil {
    fmt.Println(&quot;unable to get PORT environment variable, falling back to 8080&quot;)

    // Use =, not :=
    // Otherwise it&#39;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(&quot;PORT&quot;) != &quot;&quot; {
    var err error
    port, err = strconv.Atoi(os.Getenv(&quot;PORT&quot;))
	if err != nil {
		fmt.Fprintf(os.Stderr, &quot;error: unable to get PORT environment variable: %v\n&quot;, 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 Emulate OR operator in variable declaration from Javascript in Go

huangapple
  • 本文由 发表于 2017年5月23日 00:47:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/44118191.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定