반응형
Go에서 여러 반환 값에 대한 변환 / 유형 어설 션을 수행하는 관용적 방법
Go에서 여러 반환 값을 캐스팅하는 관용적 방법은 무엇입니까?
한 줄로 수행 할 수 있습니까? 아니면 아래 예제에서 수행 한 것과 같은 임시 변수를 사용해야합니까?
package main
import "fmt"
func oneRet() interface{} {
return "Hello"
}
func twoRet() (interface{}, error) {
return "Hejsan", nil
}
func main() {
// With one return value, you can simply do this
str1 := oneRet().(string)
fmt.Println("String 1: " + str1)
// It is not as easy with two return values
//str2, err := twoRet().(string) // Not possible
// Do I really have to use a temp variable instead?
temp, err := twoRet()
str2 := temp.(string)
fmt.Println("String 2: " + str2 )
if err != nil {
panic("unreachable")
}
}
그건 그렇고, casting
인터페이스에 관해서는 호출 됩니까?
i := interface.(int)
한 줄로 할 수는 없습니다. 임시 변수 접근 방식은 갈 길입니다.
그건 그렇고, 인터페이스에 관해서는 캐스팅이라고 부릅니까?
실제로 유형 어설 션 이라고합니다 . 유형
캐스트
변환은 다릅니다.
var a int
var b int64
a = 5
b = int64(a)
func silly() (interface{}, error) {
return "silly", nil
}
v, err := silly()
if err != nil {
// handle error
}
s, ok := v.(string)
if !ok {
// the assertion failed.
}
그러나 실제로 원하는 것은 다음과 같이 유형 스위치를 사용하는 것입니다.
switch t := v.(type) {
case string:
// t is a string
case int :
// t is an int
default:
// t is some other type that we didn't name.
}
Go는 간결함보다는 정확성에 관한 것입니다.
template.Must is the standard library's approach for returning only the first return value in one statement. Could be done similarly for your case:
func must(v interface{}, err error) interface{} {
if err != nil {
panic(err)
}
return v
}
// Usage:
str2 := must(twoRet()).(string)
By using must
you basically say that there should never be an error, and if there is, then the program can't (or at least shouldn't) keep operating, and will panic instead.
Or just in a single if:
if v, ok := value.(migrater); ok {
v.migrate()
}
Go will take care of the cast inside the if clause and let you access the properties of the casted type.
반응형
'IT박스' 카테고리의 다른 글
C # 기본 키워드의 F #에 해당하는 것은 무엇입니까? (0) | 2020.11.05 |
---|---|
Google 크롬 백그라운드 스크립트를 디버그하는 방법은 무엇입니까? (0) | 2020.11.05 |
Spring RedirectAttributes : addAttribute () 대 addFlashAttribute () (0) | 2020.11.05 |
Docker 아래에 설치할 때 대화 상자 질문에 대답 할 수 있습니까? (0) | 2020.11.05 |
RecyclerView의 Android setOnScrollListner는 더 이상 사용되지 않습니다. (0) | 2020.11.05 |