go - 构造奇怪的行为
问题描述
我刚开始玩 Go-lang 并遇到了它的奇怪行为 Structs。我有一个 StructA
和另一个 Struct B
,在 Struct 中B
定义为[]A
问题的一个键是在分配新实例类型的值时,尽管类型相同,但它的B
元素会抛出错误。A
任何帮助将不胜感激在下面我粘贴导致错误的最小代码
package main
import (
"fmt"
"math"
"github.com/shirou/gopsutil/disk"
"strconv"
)
func main() {
/************ disk details goes here ************/
diskPartitions, err := disk.Partitions(true)
dealwithErr(err)
fmt.Println(diskPartitions)
type PARTITIONLIST []PARTITION
var partitionsList PARTITIONLIST
for partitionIndex, partition := range diskPartitions {
partitionStat, err := disk.Usage(partition.Mountpoint)
dealwithErr(err)
var partitionDetails = PARTITION{
"PARTITION",
partitionIndex,
partition.Mountpoint,
"" + fmt.Sprint(partitionStat.Total) + " and " + bytesToSize(partitionStat.Total),
"" + fmt.Sprint(partitionStat.Used) + " and " + bytesToSize(partitionStat.Used),
"" + fmt.Sprint(partitionStat.Free) + " and " + bytesToSize(partitionStat.Free),
"" + fmt.Sprint(partitionStat.UsedPercent) + "and " + strconv.FormatFloat(partitionStat.UsedPercent, 'f', 2, 64),
}
partitionsList = append(partitionsList, partitionDetails)
}
//till here working fine
fmt.Println(partitionsList)
//THE BELOW TWO LINES ERROR IS THE ACTUAL ERROR I AM ASKING
var partitionDetails = PARTITIONS{
"partitions",
partitionsList
}
dealwithErr(err)
}
/************ all struct goes here ************/
type PARTITION struct {
Name string
Partition_index int
Partition string
Total_space_in_bytes string
Used_space_in_bytes string
Free_space_in_bytes string
Percentage_space_usage string
}
type PARTITIONLIST []PARTITION
type PARTITIONS struct {
Name string
List []PARTITIONS
}
/************ helper functions goes below here ************/
func bytesToSize(bytes uint64) string {
sizes := []string{"Bytes", "KB", "MB", "GB", "TB"}
if bytes == 0 {
return fmt.Sprint(float64(0), "bytes")
} else {
var bytes1 = float64(bytes)
var i = math.Floor(math.Log(bytes1) / math.Log(1024))
var count = bytes1 / math.Pow(1024, i)
var j = int(i)
var val = fmt.Sprintf("%.1f", count)
return fmt.Sprint(val, sizes[j])
}
}
func dealwithErr(err error) {
if err != nil {
fmt.Println(err)
}
}
编辑:该错误正在运行时
意外的换行符,需要逗号或 }
并且那个警告编辑器显示在 IDE 上
不能使用 partitionsList(类型 PARTITIONSLIST)作为类型 []PARTITIONS
解决方案
考虑,阅读这篇文章并改变你的命名风格,
花时间决定什么是专有名称。
你已经声明PARITIONLIST
了两次
type PARTITIONLIST []PARTITION //17th line, remove this
PARTITIONS
定义为,
type PARTITIONS struct {
Name string
List []PARTITION
}
您可以使用字段PARTITIONLIST
代替[]PARTITION
类型List
。
结构变量字段值以逗号结尾,
var partitionDetails = PARTITIONS{
"partitions",
partitionsList,
}
推荐阅读
- android - Android TV Receiver App 无法根据我的投射控制台中的配置启动
- npm - 如何使用 NPM 导入 AlpineJS?
- android - NavigationView.setNavigationItemSelectedListener 不工作
- android - 从前台状态转到后台状态不会收到 firebase 通知
- python - 比较数据框中的两列,如果值不同,则从另一列给出特定值
- reactjs - 无限的孩子
- pandas - 基于多个索引重采样到等距时间
- json - 发送多个请求 webhook 团队
- android - Android:可绘制的环形多梯度
- javascript - 停止 babel 解析并生成重新格式化的输出代码