假设我有这样的代码:
type CustomStringType string
var a *CustomStringType
x := CustomStringType("sample string")
a = &x
var b *string
我无法修改上面代码中的任何内容。
现在我想分配a
给b
我尝试过多种方法,例如:
b = a
b = string(a)
b = a.(string)
b = a.(*string)
但它们都没有真正起作用。
假设我有这样的代码:
type CustomStringType string
var a *CustomStringType
x := CustomStringType("sample string")
a = &x
var b *string
我无法修改上面代码中的任何内容。
现在我想分配a
给b
我尝试过多种方法,例如:
b = a
b = string(a)
b = a.(string)
b = a.(*string)
但它们都没有真正起作用。
使用简单的类型转换:
由于要转换的类型以运算符开头
*
,因此必须将其括起来以避免歧义(例如,您要转换为*string
, 而不是转换为string
并取消引用结果)。(*string)(a)
是有效的转换,因为您想要将值从类型转换*CustomStringType
为*string
,并且规范允许使用以下规则进行此类转换:和
*CustomStringType
都是*string
未命名的指针类型,并且都具有string
指针基类型。您可以使用go.dev 文档的转换:
但让我们看看这个注释
所以解决方案可以是: