Golang中无法在结构体字面量中使用types.NewDecimal(5,1)(类型为types.Decimal)作为types.Decimal值的问题

Golang中无法在结构体字面量中使用types.NewDecimal(5,1)(类型为types.Decimal)作为types.Decimal值的问题 你好,我是Go语言的新手,无法理解这条错误信息。作为错误信息的一部分,被赋值的值和期望的类型都是Decimal,但它仍然报错。

“cannot use types.NewDecimal(5, 1) (value of type types.Decimal) as types.Decimal value in struct literal”

错误信息:

“owner”: “_generated_diagnostic_collection_name_#0”,
“code”: {
    “value”: “IncompatibleAssign”,
    “target”: {
        “$mid”: 1,
        “external”: “https://pkg.go.dev/golang.org/x/tools/internal/typesinternal?utm_source%3Dgopls#IncompatibleAssign”,
        “path”: “/golang.org/x/tools/internal/typesinternal”,
        “scheme”: “https”,
        “authority”: “pkg.go.dev”,
        “query”: “utm_source=gopls”,
        “fragment”: “IncompatibleAssign”
    }
},
“severity”: 8,
“message”: “cannot use types.NewDecimal(5, 1) (value of type types.Decimal) as types.Decimal value in struct literal”,
“source”: “compiler”,
“startLineNumber”: 33,
“startColumn”: 27,
“endLineNumber”: 33,
“endColumn”: 49

更多关于Golang中无法在结构体字面量中使用types.NewDecimal(5,1)(类型为types.Decimal)作为types.Decimal值的问题的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

你能分享一下有问题的代码吗?

提到 internal 让我有些疑惑……

更多关于Golang中无法在结构体字面量中使用types.NewDecimal(5,1)(类型为types.Decimal)作为types.Decimal值的问题的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


感谢。能够找到根本原因。实际上,我在 GOPATH 环境变量中配置了两个路径(路径1 和 路径2),并且包 “types” 同时存在于这两个路径中。因此,在我的代码中,赋值语句的左侧指向了路径1,而右侧指向了路径2。尽管这两个包在代码层面是相同的,但 Go 仍然会报错。

一旦我从路径2中移除了该包,问题就解决了。

这个问题通常是因为类型别名或包导入导致的类型不匹配。虽然表面上都是 types.Decimal 类型,但可能来自不同的包或存在类型定义差异。

示例代码:

package main

import (
    "fmt"
    "github.com/shopspring/decimal"  // 假设这是你的types包
)

type MyStruct struct {
    Amount decimal.Decimal
}

func main() {
    // 错误示例:如果decimal来自不同的包或类型定义
    // s := MyStruct{
    //     Amount: types.NewDecimal(5, 1),  // 这里会报错
    // }
    
    // 正确示例:确保使用相同包下的类型
    s := MyStruct{
        Amount: decimal.NewFromFloat(5.1),
    }
    
    fmt.Println(s.Amount)
}

检查你的导入语句,确保 types.NewDecimal 返回的类型和结构体字段的类型来自同一个包。使用 go doc 或查看包文档确认类型定义是否一致。

回到顶部