问题
I was looking for how to cast the interface to a struct, but I do not how I can not do it.
I will try to explain my problem.
type Result struct {
Http_code int
Http_msg string
Response interface{}}
This structure is returned by a function that makes an HTTP request to the server, on the other hand, I have different types of structure to wrap the response.
And this is the struct which I want to cast the interface.
type ResHealth struct {
Type string
Get_health struct {
Healthy bool
}}
My problem is that when I try to make the assertion, I always get either segment violation or the program doesn't compile.
The workflow is:
package test
type Result struct {
Http_code int
Http_msg string
Response interface{}
}
type ResHealth struct {
Type string
Get_health struct {
Healthy bool
}
}
func Do() Result {
var http_response Result
var health ResHealth
+++do something+++
http_response.Response = health
return http_response
}
package Test2
aux := post.Do()
aux.Response.(ResHealth) // here I have either segment violation or the program doesn't compile
/////
回答1:
Using type assertions you can do this:
package main
import (
"fmt"
)
type I interface {
F()
}
type C struct {
}
func (_ *C) F() {}
func main() {
var i I = &C{}
var c *C = i.(*C)
fmt.Println(c)
}
The major problem with type assertions like this is that they are unsafe which means that if the type can't be "asserted" correctly at runtime it'll panic. This sucks. Especially for things like where functions return error
but return a concrete Error type to give you additional information but when you use a type assertion like this you have to hope the devs never change the concrete Error type or you'll run into unexpected runtime panics in the future (because the program will still build). You can partially mitigate this by using safe type assertions:
func main() {
var i interface{} = &D{}
c, ok := i.(*C)
if ok {
fmt.Println(c)
} else {
fmt.Println("oops")
}
}
Also: Don't confuse type casts with type assertions. They are not the same thing!
A type assertion is basically just saying the compiler "this is X" not "convert this to X". A type cast is saying "convert this to X". Although, it's not actually a "cast" as go calls them "conversions".
回答2:
Thanks for the help, I fix it the problem.
When I was doing the assertion, I was casting with the wrong struct... So the way to fix the problems is:
aux := post.Do()
aux.Response.(ResHealth) ==> aux.Response.(test.ResHealth)
Now it's working. Thank you
来源:https://stackoverflow.com/questions/50852393/how-to-cast-interface-to-struct