|
|
|
|
|
by crawshaw
3950 days ago
|
|
There are several ways to solve this in Go. The first that comes to mind, assuming you want to truncate to the first 12 runes, not bytes: func main() {
v := []rune(os.Args[1])
if len(v) > 12 {
v = v[:12]
}
fmt.Println(string(v))
}
Or more in the spirit of the C example in the post: func main() {
res := make([]rune, 12)
copy(res, []rune(os.Args[1]))
fmt.Println(string(res))
}
Note that res will stay on the stack, just like C.I expect the author is trying to say something about Go that I'm not quite getting. Perhaps that it is not an expression-based language, so to make code readable you need to make use of multiple statements. That's by design, but I understand it may be unappealing if you want to program in an expression-heavy style. |
|
I assume "Go sucks because, look, this one weird case is a bit ugly." (that is, as rhetoric, not dialectic; it is not literally claiming "one case bad" -> "Go is bad" in the logical sense.) A weird case that I've programmed many thousands of lines of Go code in but never once encountered. Taking a slice out of a string blind like that is actually a bit rare; usually in some way it turns out you actually have length information somewhere in the environment. It's hardly like "slice index out of bounds" is some sort of terrible error... it is, at least, arguable that Python is in the wrong here for being so willing to return a string generated by [0:12] that is not 12 bytes/characters in length, which seems like a reasonable assumption to make of such an operation.
Now, if we want to talk about little examples like this, let's talk about sending on something like a channel in Python, to say nothing of Python's implementation of the "go" keyword... oh, yes, I see, suddenly this is an unfair way to compare languages.
Yes, it is.