将一个从其他包中声明的结构体赋值一个值。

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

Assign a value to a struct which was declare from other package

问题

这是我的代码。
我将我的结构体OperatInfo提取到struct.go中,并希望在worker.go中的main包中使用这个结构体。

struct.go

package batch

type OperatInfo struct {
    eventId     string
    hallId      string
    userId      string
    operating   string
    operatingID string
    ip          string
}

worker.go

package main

import (
    "time"
    "fmt"
    "strconv"
    "./kernel/api"
    "./kernel/db"
    "./batch/basic"
    "./batch/struct"
)

var operatInfo batch.OperatInfo

func BatchDeposit(eventId string, userId string, hallId string, operating string, operatingID string, ip string) {
    // 我在这里遇到了一个错误
    operatInfo.eventId = eventId
    operatInfo.hallId = hallId
    operatInfo.userId = userId
    operatInfo.operating = operating
    operatInfo.operatingID = operatingID
    operatInfo.ip = ip
}

我只是无法设置operatInfo的字段。

有任何建议或提示将会有所帮助。谢谢。

英文:

Here is my code.
I extract my struct OperatInfo to the struct.go and wanna to use this struct in the main package which in worker.go.

struct.go

package batch

type OperatInfo struct {
	eventId string
	hallId string
	userId string
	operating string
	operatingID string
	ip string
}

worker.go

package main

import (
	"time"
	"fmt"
	"strconv"
	"./kernel/api"
	"./kernel/db"
	"./batch/basic"
	"./batch/struct"
)

var operatInfo batch.OperatInfo

func BatchDeposit(eventId string, userId string, hallId string, operating string, operatingID string, ip string) {
    // I get an error here
	operatInfo.eventId = eventId
	operatInfo.hallId = hallId
	operatInfo.userId = userId
	operatInfo.operating = operating
	operatInfo.operatingID = operatingID
	operatInfo.ip = ip
}

I just can't set operatInfo fields.

Any suggestions or tips will helps. Thanks.

答案1

得分: 1

只有以大写字母开头的字段才是公开可见的。
要解决您的问题,您可以为每个字段创建getter和setter,或者按照以下方式重命名字段的结构:

type OperatInfo struct {
    EventId      string
    HallId       string
    UserId       string
    Operating    string
    OperatingID  string
    Ip           string
}
英文:

Only the fields that starts with an upper case letter are public visible.
To solve your problem you can create getter and setter for each field or rename your fields' struct as follow:

type OperatInfo struct {
    EventId string
    HallId string
    UserId string
    Operating string
    OperatingID string
    Ip string
}

huangapple
  • 本文由 发表于 2017年8月10日 18:07:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/45610700.html
匿名

发表评论

匿名网友

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

确定