doumen9709 2015-01-26 23:22
浏览 28
已采纳

将地图传递到导入的Golang包中的函数时出错

I need to send a map to a function declared in a imported package, and keep getting this error:

./main.go:21: cannot use m (type map[string]ticket) as type map[string]some_package.ticket in function argument

This is the code of main.go in golang GOPATH folder:

package main

import (    
        "time"
         sp "./some_package"
        )

type ticket struct {
  Timestamp int64
  Identification_number int
}
var m map[string]ticket


func main() {
  humans := 10
  m = make(map[string]ticket)
  m["ticket1"] = ticket{time.Now().Unix(), 1234}
  sp_ := sp.New(humans)
  sp_.SetTicket(m)
}

And this is the code of some_package.go in /some_package in golang GOPATH folder:

package some_package

type park struct{
  card map[string]ticket
  people int
}

type ticket struct {
  Timestamp int64
  Identification_number int
}

func (p *park) SetTicket(m map[string]ticket)(){

}

func New(humans int)(p *park){
  p.card = make(map[string]ticket)
  p.people = humans
  return p
}

How should I pass the value of the map to the imported package function or get the map value inside the function from the parent package? Is this even possible or is there a workaround?

  • 写回答

1条回答 默认 最新

  • dongxiong5546 2015-01-26 23:29
    关注

    Even though the two types are named the same and contain the same structure, they are not the same type. A type always belongs to a package, and those two types belong to different packages.

    So you shouldn't copypaste the type ticket from some_package to main, but instead 1. export it to other packages by naming it in uppercase: type Ticket struct; and 2. use it from main like make(map[string]sp.Ticket).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DEV-C++编译缺失
  • ¥33 找熟练码农写段Pyhthon程序
  • ¥100 怎么让数据库字段自动更新
  • ¥15 antv g6 力导向图布局
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数
  • ¥15 关于#线性回归#的问题:【统计】回归系数要转化为相关系数才能进行Fisher' Z转化吗(相关搜索:回归模型)