Golang中错误:无法在切片字面量中使用*{...}(类型*)作为*类型
Golang中错误:无法在切片字面量中使用*{…}(类型*)作为*类型 大家好,社区的朋友们。
这是我第一次发帖和编写Go语言代码。 我正在创建一个Go结构体。 结构体的类型是正确的,但结构体的初始化却出现了错误。 我多次在结构体中嵌套使用了其他结构体。 这里是包含示例的Go Playground链接。
显示的错误是:./prog.go:45:4: undefined: Amount ./prog.go:45:4: cannot use TheAmount{...} (type TheAmount) as type PurchaseUnits in slice literal
每个字段我都遇到了同样的错误,我该如何解决这个问题呢?
谢谢朋友们!
更多关于Golang中错误:无法在切片字面量中使用*{...}(类型*)作为*类型的实战教程也可以访问 https://www.itying.com/category-94-b0.html
感谢您的回复。 现在可以正常工作了。 对于货币类型,我应该使用 int 还是其他类型?
更多关于Golang中错误:无法在切片字面量中使用*{...}(类型*)作为*类型的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Go中,我建议将美分存储为整数数据类型之一(int64、int32、int等)。
Purchase_units 字段的类型是 []PurchaseUnits,但你在其中放置了像 Address 这样的字段,就好像它是一个单一的 PurchaseUnits 结构体。如果你想要一个 PurchaseUnits 切片,那么在第 44 行的 []PurchaseUnits 内部添加第二组 { 和 }。
此外,在处理货币时不应使用浮点数。
根据你提供的错误信息和代码示例,问题在于结构体字段类型不匹配。让我们分析一下具体原因和解决方案。
在你的代码中,PurchaseUnits 字段期望的是 []PurchaseUnits 类型,但你尝试使用 TheAmount 类型的值来初始化它。以下是修正后的代码:
package main
import "fmt"
type Amount struct {
CurrencyCode string `json:"currency_code"`
Value string `json:"value"`
}
type PurchaseUnits struct {
Amount Amount `json:"amount"`
ReferenceID string `json:"reference_id"`
Description string `json:"description"`
CustomID string `json:"custom_id"`
InvoiceID string `json:"invoice_id"`
SoftDescriptor string `json:"soft_descriptor"`
}
type Order struct {
Intent string `json:"intent"`
PurchaseUnits []PurchaseUnits `json:"purchase_units"`
}
func main() {
order := Order{
Intent: "CAPTURE",
PurchaseUnits: []PurchaseUnits{
{
Amount: Amount{
CurrencyCode: "USD",
Value: "100.00",
},
ReferenceID: "ref_id_1",
Description: "Test purchase",
CustomID: "custom_1",
InvoiceID: "inv_1",
SoftDescriptor: "Test",
},
},
}
fmt.Printf("%+v\n", order)
}
关键修改点:
- 修正类型定义:
PurchaseUnits现在是一个结构体类型,而不是之前的TheAmount别名 - 修正切片初始化:
PurchaseUnits字段现在正确初始化为[]PurchaseUnits切片 - 结构体嵌套:
Amount结构体作为PurchaseUnits的一个字段
如果你需要保持原有的类型别名,可以这样修改:
type TheAmount = Amount
type PurchaseUnits struct {
Amount TheAmount `json:"amount"`
ReferenceID string `json:"reference_id"`
Description string `json:"description"`
CustomID string `json:"custom_id"`
InvoiceID string `json:"invoice_id"`
SoftDescriptor string `json:"soft_descriptor"`
}
这样就能解决类型不匹配的错误,确保结构体初始化时类型正确对应。

