在使用继承结构时,出现了Golang类型不匹配的问题。

huangapple go评论60阅读模式
英文:

golang type mismatch when using inherited struct

问题

type MongoDBConfig struct {
    *mgo.DialInfo
}

func ConfigureMongoDB() (*MongoDBConfig, error) {
    // 获取 GOPATH
    GOPATH := os.Getenv("GOPATH")

    file, err := os.Open(GOPATH + RESOURCE_PATH)

    if err != nil {
        return nil, err
    }
    decoder := json.NewDecoder(file)

    mongoConfig := MongoDBConfig{}

    er := decoder.Decode(&mongoConfig)

    if er != nil {
        return nil, er
    }
    return &mongoConfig, nil
}

func InitMongoDB() (*Session, error) {

    mongoConfig, err := ConfigureMongoDB()

    if err != nil {
        return nil, err
    }

    session, mongoerr := mgo.DialWithInfo(mongoConfig)
}

在最后一行传递 mongoConfig 时出现错误。我使用 DialInfo 类型创建了 MongoDBConfig 的结构类型。

无法将 mongoConfig(类型为 *MongoDBConfig)用作 *DialInfo 类型。

英文:
    type MongoDBConfig struct {
	*mgo.DialInfo
}

func ConfigureMongoDB() (*MongoDBConfig, error) {
	//Get gopath

	GOPATH := os.Getenv("GOPATH")

	file, err := os.Open(GOPATH+RESOURCE_PATH)

	if err != nil {
		return nil, err
	}
	decoder := json.NewDecoder(file)

	mongoConfig := MongoDBConfig{}

	er := decoder.Decode(&mongoConfig)

	if er != nil {
		return nil, er
	}
	return &mongoConfig, nil
}

func InitMongoDB() (*Session, error){

	mongoConfig, err := ConfigureMongoDB()

	if err != nil {
		return nil, err
	}

	session, mongoerr := mgo.DialWithInfo(mongoConfig)

}

Getting error in the last line while passing mongoConfig. I created the struct type of MongoDBConfig using DialInfo type.

> Cannot use mongoConfig (type * MongoDBConfig) as type *DialInfo

答案1

得分: -1

显式访问嵌入字段:

session, mongoerr := mgo.DialWithInfo(mongoConfig.DialInfo)

英文:

Access embeded field explicitly:

 session, mongoerr := mgo.DialWithInfo(mongoConfig.DialInfo)

huangapple
  • 本文由 发表于 2017年8月1日 16:17:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/45432483.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定