gop icon indicating copy to clipboard operation
gop copied to clipboard

Syntax support: a if cond else b

Open wangkuiyi opened this issue 4 years ago • 1 comments

During the prototyping of Go+Torch, I noticed many Python AI programmers use Python's form of C's ? :. For example

device = torch.cuda_device(0) if opt.cuda else torch.cpu_device()

This pattern is so commonly used by Python programmers that I am expecting that Go+ could have a match. Also, Go's way is really lengthy and might call torch.xxx_device twice.

device := torch.cpu_device()
if opt.cuda {
     device = torch.cuda_device(0)
}

If we want to avoid the possibility of twice calls, we'd have to adopt an even more lengthy way:

var device torch.Device
if opt.cuda {
     device = torch.cpu_device()
} else {
     device = torch.cuda_device(0)
}

I heart that Go Authors avoided the introduction of C's ? : syntax for some reason, but could we follow Python and give the ? : a more readable form.

wangkuiyi avatar Aug 03 '20 19:08 wangkuiyi

This doesn't really look like go to me. This would make code easier to write, but at the cost of being harder to read. I also don't like the idea of overloading keywords like this. I think some variation of this that only works for variable initialization is worth consideration. But not this, and certainly not before we get some basic things implemented, like custom types.

lolbinarycat avatar Aug 05 '20 19:08 lolbinarycat