在赋值之后进行转换是可能的吗?

huangapple go评论79阅读模式
英文:

Is it possible to do a conversion after assignment?

问题

我想知道是否有任何技巧可以避免使用xv标识符/分配。基本上就像是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)
}
英文:

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)
    }

答案1

得分: 1

例如,只有x逃逸到堆上,

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)
}

输出:

1
英文:

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

答案2

得分: 0

不,我相信没有这样的技巧。

当我想要避免在作用域中声明不必要的变量,并且对于一次性操作时,我有时会使用这种匿名函数调用:

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)
}

另一方面,如果您需要在许多情况下执行类似的转换,并且不一定总是作为相同调用的结果(例如Atoi),您可以创建一个简单的函数,该函数将执行转换并通过错误:

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)
}
英文:

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)
}

huangapple
  • 本文由 发表于 2015年6月12日 21:52:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/30804797.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定