如何将接口{}强制转换为struct [英] How to cast interface {} to struct

查看:89
本文介绍了如何将接口{}强制转换为struct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找如何将接口强制转换为结构,但我不是无法做到这一点。

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

此结构由向服务器发出HTTP请求的函数返回,而我具有不同类型的结构来包装响应。

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.

工作流程为:

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
/////


推荐答案

使用类型断言可以执行以下操作:

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

像这样的类型断言的主要问题是它们是不安全的,这意味着如果在运行时不能正确地断言类型,它将引起恐慌。糟透了特别是对于函数返回 error 但返回具体的Error类型以提供其他信息的事情,但是当您使用这样的类型断言时,您必须希望开发人员不要更改具体的错误类型,否则您将来会遇到意外的运行时紧急情况(因为该程序仍会生成)。您可以通过使用安全类型声明来部分缓解此问题:

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!

类型断言基本上只是在说编译器这是X而不是将其转换为X。类型强制转换说将其转换为X。虽然,实际上它并不是真正的转换,因此被称为转换。

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".

这篇关于如何将接口{}强制转换为struct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆