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

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

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路