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 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入