无法将struct元素分配为Google / uuid数据类型

问题描述

我在项目中使用https://github.com/google/uuid,并且希望我的用户结构具有一个ID作为UUID,但不允许我将其分配为数据类型。当我尝试这样做时,出现错误Syntax error: unexpected :,expecting type。这是我的代码供参考:

package postgres

import (
  "time"
  "github.com/google/uuid"
)

type DbUser struct {
  ID: uuid.UUID,Username: string,Password: string,Email: string,DateOfBirth: time,dateCreated: time,}

有人可以帮助我阐明将struct元素或变量作为UUID传递的语法吗?

解决方法

您的struct definition是错误的,您正在使用composite literal的语法。 应该是:

type DbUser struct {
  ID uuid.UUID
  Username string
  Password string
  Email string
  DateOfBirth time.Time
  dateCreated time.Time
}

还要注意,time不是一种类型,它是程序包名称。

您可能想使用Tour of Go来学习基本语法。

,

time是程序包名称,无法在字段中定义,您应该使用time.Time。

import (
      "time"
      "github.com/google/uuid"
    )
    
    type DbUser struct {
        ID          uuid.UUID
        Username    string
        Password    string
        Email       string
        DateOfBirth time.Time
        dateCreated time.Time
    }