Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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はない ―― 代わりの書き方 では諦めるしかない旨が書かれてますが・・・。

ikyu
「こころに贅沢を」をコンセプトに一休.com、一休レストランなどのサービスを提供しています。
https://www.ikyu.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした