34
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go の変数初期化に伴う条件分岐をもっと良い感じに書きたいと思ったが諦めるしかないようです

Last updated at Posted at 2014-09-14

Go にはスクリプト言語でいうところの variable = a || b のような構文や三項演算子がないようなので、

var accessKeyId, secretAccessKey string
if config["aws_access_key_id"] == "" {
	accessKeyId = os.Getenv("AWS_ACCESS_KEY_ID")
	secretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
} else {
	accessKeyId = config["aws_access_key_id"]
	secretAccessKey = config["aws_secret_access_key"]
}

とか

var url string
var err error

if len(os.Args) == 1 {
	url, err = gozo.SendCapture()
} else {
	url, err = gozo.SendFile(os.Args[1])
}

こんな感じのコードを毎回書くことになるんだけど、本当は

accessKeyId = config["aws_access_key_id"] || os.Getenv("AWS_ACCESS_KEY_ID")
secretAccessKey = config["aws_secret_access_key"] || os.Getenv("AWS_SECRET_ACCESS_KEY")

とか

url, err := len(os.Args) == 1 ? gozo.SendCapture() : gozo.SendFile(os.Args[1])

みたいに書けたらいいと思ってますができません。それは諦めるとしてもちっとまともに書きたいんですがみなさんどうしてるんでしょうか。

Goには三項演算子a?b:cはない ―― 代わりの書き方 では諦めるしかない旨が書かれてますが・・・。

34
33
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?