gpt4 book ai didi

go - 具有未导出字段的结构类型之间的转换

转载 作者:行者123 更新时间:2023-12-05 03:17:33 28 4
gpt4 key购买 nike

来自specs on conversion , 我读了

A non-constant value x can be converted to type T in any of these cases:

  • [..]
  • ignoring struct tags (see below), x's type and T are not type parameters but have identical underlying types.
  • [..]

根据上面的规范,我本以为可以编译以下代码

package main

import "github.com/fxtlabs/date"

type Date struct {
day int32
}

func main() {
_ = date.Date(Date{12345})
}

但是,它没有编译错误信息

无法将 Date{...}(Date 类型的值)转换为 date.Date 类型

请注意 "github.com/fxtlabs/date".Date 已定义 here作为

type Date struct {
// day gives the number of days elapsed since date zero.
day int32
}

为什么编译失败?是因为 "github.com/fxtlabs/date".Date 的字段 day 没有导出吗?如果是,是否应该在规范中指定?

最佳答案

Is it because the field day from "github.com/fxtlabs/date".Date is unexported?

是的。

If yes, shouldn't this be specified in the specs?

它在 Type Identity 下的规范中.

Two struct types are identical if they have the same sequence of fields, and if corresponding fields have the same names, and identical types, and identical tags. Non-exported field names from different packages are always different.

换句话说,底层类型并不相同,因为它们的字段未导出

相同类型的示例 struct {Day int32}(packag a)和 struct{Day int32}(package b)。不相同类型的示例 struct {day int32}(packag a)和 struct{day int32}(package b)。

关于go - 具有未导出字段的结构类型之间的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74123155/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com