相关疑难解决方法(0)

如何在Go中使用文字*int64?

我有一个带*int64字段的结构类型.

type SomeType struct {
    SomeField *int64
}
Run Code Online (Sandbox Code Playgroud)

在我的代码中的某个时刻,我想声明一个这样的文字(比如,当我知道所述值应为0,或者指向0时,你知道我的意思)

instance := SomeType{
    SomeField: &0,
}
Run Code Online (Sandbox Code Playgroud)

...除了这不起作用

./main.go:xx: cannot use &0 (type *int) as type *int64 in field value
Run Code Online (Sandbox Code Playgroud)

所以我试试这个

instance := SomeType{
    SomeField: &int64(0),
}
Run Code Online (Sandbox Code Playgroud)

......但这也行不通

./main.go:xx: cannot take the address of int64(0)
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?我能想出的唯一解决方案是使用占位符变量

var placeholder int64
placeholder = 0

instance := SomeType{
    SomeField: &placeholder,
}
Run Code Online (Sandbox Code Playgroud)

注意:当它是*int而不是a时,&0语法工作正常*int64.编辑:不,不.为此表示歉意.

编辑:

显然,我的问题含糊不清.我正在寻找一种方法来说明一个*int64.这可以在构造函数中使用,或者用于表示文字结构值,或者甚至作为其他函数的参数.但帮助函数或使用不同的类型不是我正在寻找的解决方案.

struct pointers literals go

79
推荐指数
3
解决办法
4万
查看次数

如何从函数调用中获取返回值的指针?

我只需要一个指向time.Time的指针,所以下面的代码似乎无效:

./c.go:5:不能取时间地址.现在()

我只是想知道为什么?有没有办法做到这一点,除了先对变量赋值并获取变量的指针?

package main

import "time"
func main() {
    _ = &time.Now()
}
Run Code Online (Sandbox Code Playgroud)

pointers go

20
推荐指数
3
解决办法
6704
查看次数

如何在Go中存储对操作结果的引用?

好吧用文字描述它很难,但是假设我有一个存储int指针的地图,并希望将操作的结果存储为我的哈希中的另一个键:

m := make(map[string]*int)

m["d"] = &(*m["x"] + *m["y"])
Run Code Online (Sandbox Code Playgroud)

这不起作用,并给我错误: cannot take the address of *m["x"] & *m["y"]

思考?

dictionary pointers go

7
推荐指数
1
解决办法
1464
查看次数

如何在 DataStore 中存储 *time.Time 类型的结构体字段的当前时间?

根据我的要求,我创建了一个结构体 -

type MyRule struct {
   CreatedAt    time.Time  `json:"createdAt" datastore:"createdAt,noindex"`
   UpdatedAt    *time.Time  `json:"updatedAt" datastore:"updatedAt,noindex"`
}
Run Code Online (Sandbox Code Playgroud)

对于createdAt字段,我可以将当​​前时间存储为-

MyRule.CreatedAt = time.Now()
Run Code Online (Sandbox Code Playgroud)

但是,同样的方法无法将当前时间存储在structupdatedAt字段中MyRule,因为它的类型为 is*time.Time和 not time.Time。在这里,我无法更改 的字段类型,updatedAt因为允许我在创建任何规则时*time.Time接受 nil 作为值。updatedAt

如果我尝试这样做-

 MyRule.UpdatedAt = time.Now()
Run Code Online (Sandbox Code Playgroud)

它给了我以下错误-

 cannot use time.Now()(type time.Time) as type *time.Time in assignment
Run Code Online (Sandbox Code Playgroud)

如何将当前时间值存储在类型为 *time.Time 而不是 time.Time 的 UpdatedAt 字段中

go

1
推荐指数
1
解决办法
2116
查看次数

标签 统计

go ×4

pointers ×3

dictionary ×1

literals ×1

struct ×1