duandu2159 2017-12-12 14:30
浏览 10
已采纳

数据存储区不会在Go中放入嵌套结构

The structs look like this:

type Account struct {
  Username         string    // NameKey
  Password         []byte    `datastore:",noindex"`
  RegistrationTime time.Time `datastore:",noindex"`
  AppUser
}

type AppUser struct {
  LoginEntries []LoginEntry `datastore:",noindex"`
}

type LoginEntry struct {
  Timestamp time.Time `datastore:",noindex"`
  UserAgent string    `datastore:",noindex"`
  IP        string    `datastore:",noindex"`
}

I'm also sure I put the data correctly, because other data has no problem being updated, and I tried to fmt.Println the content of account Account right before saving it in datastore (Put(ctx, key, &account) and when I print it then I can see all the AppUser information.. but when I later Get the user then the AppUser info doesn't exist (just shows up as {[]}).

I'm quite certain I have stored nested struct slices before in datastore without any problems, so I'm quite confused as to what might be causing it..


The Put func:

func PutAccount(ctx context.Context, acc Account) (*datastore.Key, error) {
  if isValidUsername(acc.Username) != true {
    return nil, errors.New("Invalid username.")
  }
  var hashedPassword []byte
  if acc.RegistrationTime.IsZero() {
    var err error
    hashedPassword, err = bcrypt.GenerateFromPassword(acc.Password, 12)
    if err != nil {
      return nil, err
    }
  } else {
    hashedPassword = acc.Password
  }
  account := Account{
    Username:         strings.ToLower(acc.Username),
    Password:         hashedPassword,
    RegistrationTime: time.Now(),
    AppUser:          acc.AppUser}
  fmt.Println("PutAccount, account:", account) // before saving it prints the AppUser without problems
  key := datastore.NameKey("Account", account.Username, nil)
  return database.DatastoreClient().Put(ctx, key, &account)
}

the Get func:

func GetAccount(ctx context.Context, key *datastore.Key) (Account, error) {
  var account Account
  err := database.DatastoreClient().Get(ctx, key, &account)
  if err != nil {
    return account, err
  }
  return account, nil
}
  • 写回答

1条回答 默认 最新

  • dongqing344716 2017-12-12 15:26
    关注

    Using named struct works. eg:

    type Account struct {
      Username         string    // NameKey
      Password         []byte    `datastore:",noindex"`
      RegistrationTime time.Time `datastore:",noindex"`
      AppUser          AppUser
    }
    

    As to why anonymous embedded struct do not, this is probably worthy of an issue.

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

报告相同问题?

悬赏问题

  • ¥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代码和思路
  • ¥15 公交车和无人机协同运输