I'm wondering if there is any trick to avoid the xv identifier/allocation. Basically something like x, err := T1(strconv.Atoi("1"))
package main
import "fmt"
import "strconv"
type T1 int
func main() {
xv, err := strconv.Atoi("1")
if err != nil {
panic(err)
}
x := T1(xv)
fmt.Println(x)
}
For example, only x
escapes to heap,
package main
import (
"fmt"
"strconv"
)
type T1 int
func atoi(a string) int {
i, err := strconv.Atoi(a)
if err != nil {
panic(err)
}
return i
}
func main() {
x := T1(atoi("1"))
fmt.Println(x)
}
Output:
1
No, I believe there is no such trick.
When I want to avoid declarations of unnecessary variables in the scope, and for one-off operations, I sometimes use this kind of anonymous function calls:
package main
import "fmt"
import "strconv"
type T1 int
func main() {
x, err := func() (T1, error) {
x, err := strconv.Atoi("1")
return T1(x), err
}()
fmt.Println(err, x)
}
On the other hand, if you need to perform a similar cast on many occasions, and not necessarily always as a result of the same call (like Atoi
), you could create a simple function, which would do the conversion and pass through the error:
package main
import "fmt"
import "strconv"
type T1 int
func resToT1(n int, err error) (T1, error) {
return T1(n), err
}
func main() {
x, err := resToT1(strconv.Atoi("1"))
fmt.Println(err, x)
}