doy51723 2018-08-17 02:20
浏览 55
已采纳

将接口传递给函数

I'm trying to write a configuration package that takes a json filename and a configuration struct. It should unmarshal the json into the passed-in struct and return it. I'm trying to work with interfaces so I can pass any struct I want

The error is:

panic: interface conversion: interface {} is map[string]interface {}, not *main.ConfigurationData

I'm not quite sure how to solve this issue.

Here is my main package

package main

import (
    "config"
    "commons"
)

type ConfigurationData struct {
    S3ARN string `json:"S3ARN"`
    SQSQueueUrl string `json:"SQSQueueUrl"`
}

var configData *ConfigurationData

func main(){
    configData=config.Load("aws.config.json",configData).(*ConfigurationData)
    commons.Dump(configData)
}

Here is my config package

package config

import (
    "os"
    "encoding/json"
    "sync"
    "commons"
)

var configLock = new(sync.RWMutex)

func Load(filename string,config interface{})interface{} {
    file, err := os.Open(filename)
    commons.CheckErrorf(err, "Config Open Error")
    defer file.Close()
    decoder := json.NewDecoder(file)
    configLock.Lock()
    err = decoder.Decode(&config)
    commons.CheckErrorf(err, "Config Decode Error")
    configLock.Unlock()
    return config
}
  • 写回答

2条回答 默认 最新

  • dongzhang1864 2018-08-17 02:43
    关注

    This answer explains well why you get the exception.

    What you should do:

    When the encoding/json package runs into a type that implements the Marshaler interface, it uses that type’s MarshalJSON() method instead of the default marshaling code to turn the object into JSON. Similarly, when decoding a JSON object it will test to see if the object implements the Unmarshaler interface, and if so it will use the UnmarshalJSON() method instead of the default unmarshaling behavior.

    Mine solution for this would be to implement UnmarshalJSON method on *ConfigurationData and method Load should accept Unmarshaler interface instead of interface{}.

    You can read more about technics here: https://blog.gopheracademy.com/advent-2016/advanced-encoding-decoding/

    Then you simple would do json.Unmarshal(b, &config) inside the Load method where b is []byte read from file.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办