登录
首页 >  Golang >  Go问答

构造奇怪的行为

来源:stackoverflow

时间:2024-04-19 15:09:36 127浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《构造奇怪的行为》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

我刚刚开始使用 go-lang,发现了它的 structs 的奇怪行为。我有一个 struct a 和另一个 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


解决方案


正如错误明确指出的那样:

无法将partitionslist(类型partitionslist)用作类型[]partitions

结构中存在类型不匹配问题。由于 partitionslist 不符合 []partitions。因此,如果您创建这两种类型的变量,它们是不同的。

type partitionlist []partition

type partitions struct {
    name                string
    list                []partitions // here the list is slice of partitions.
}

当您创建 partitionlist 类型的切片时。

var partitionslist partitionlist // this is a variable of partitionlist type which is not equal to `[]partitions`

这是因为 golang 是严格类型语言。因此,即使两个值的基础类型相似。两者还是有区别的。更简单试试这个例子:

package main

import "fmt"

type myint int

func main() {
    var a int = 2
    var b myint = 2
    fmt.println(a==b)
}

输出:

无效操作:a == b(int 和 myint 类型不匹配)

Playground Example

因此您需要创建 []partitions 的切片:

var partitionslist `[]partitions`

或者您可以创建 partitionlist 类型的两个变量以使它们相似。

另一个错误:

意外的换行符,需要逗号或 }

是因为如果您在新行中使用它,则需要在最后一个字段之后传递 ,

var partitiondetails = partitions{
    "partitions",
    partitionslist, // pass comma here in your code.
}

完整的工作示例:

package main

import (
    "fmt"
    "math"
    "strconv"

    "github.com/shirou/gopsutil/disk"
)

func main() {

    /************ disk details goes here ************/
    diskpartitions, err := disk.partitions(true)
    dealwitherr(err)
    fmt.println(diskpartitions)

    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,
    }

    fmt.println(partitiondetails)

    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 partitionlist
}

/************ 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)
    }
}

Playground example

考虑阅读 this 并更改您的命名风格,

花点时间决定什么是专有名称。

您已声明 paritionlist 两次

type partitionlist []partition //17th line, remove this

partitions 定义为,

type partitions struct {
    name string
    list []partition
}

您可以对 list 字段使用 partitionlist 而不是 []partition 类型。

结构体变量字段值以逗号结束,

var partitionDetails = PARTITIONS{
        "partitions",
        partitionsList,
    }

好了,本文到此结束,带大家了解了《构造奇怪的行为》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>