col.ToStrings未定义(类型Columns没有字段或方法ToStrings)

huangapple go评论81阅读模式
英文:

col.ToStrings undefined (type Columns has no field or method ToStrings)

问题

我正在尝试创建一个表示指向另一种类型的指针切片的类型,并为其定义一个方法。我的代码看起来类似于这样,尽管为了示例而简化了一些:

package column

type Column struct {
    name string
}

type Columns []*Column

func (c Column) ToString() string {
    return c.name
}

func (c Columns) ToStrings() []string {
    var strSlice []string
    for _, v := range c {
        strSlice = append(strSlice, v.ToString())
    }
    return strSlice
}

然后在另一个文件中这样调用:

import (
    c "main/column"
    "strings"
)

type Columns c.Columns

func ToString(col Columns) string {
    return strings.Join(col.ToStrings(), ",\n")
}

然而,当我尝试在导出的"Columns"类型上调用方法ToStrings()时,我得到了这个错误:

columns.ToStrings undefined (type Columns has no field or method ToStrings)

似乎编译器找不到定义在"Columns"类型上的方法ToStrings()。有没有办法解决这个问题?为什么编译器找不到"Columns"类型定义的导出方法?

英文:

I am attempting to create a type that represents a slice of pointers to another type and define a method for it, my code looks similar to this, albeit a bit simplified for the example:

package column

type Column struct {

	name string
}

type Columns []*Column

func (c Column) ToString() string {
    
    return c.name
}

func (c Columns) ToStrings() []string {

	var strSlice []string

	for _, v := range c {

		strSlice = append(strSlice, v.ToString())
	}

	return strSlice
}

It is then called in a separate file like this:

import (
    c "main/column"
    "strings"
)

type Columns c.Columns

func ToString(col Columns) string {
    
    return strings.Join(col.ToStrings(), ",\n")
}

However when I try to call the method ToStrings() on the exported "Columns" type I get this error:

> columns.ToStrings undefined (type Columns has no field or method
> ToStrings)

It seems the compiler can't find the method ToStrings(). Is there a way around this? Why can't the compiler find the exported method defined for the "Columns" type?

答案1

得分: 0

type Columns c.Columns 创建了一个全新的类型,并具有新的方法集。这样做的唯一原因是为了明确地移除现有类型的方法。

英文:

type Columns c.Columns creates an entirely new type, with a new method set. The only reason to do this is to specifically remove the methods of the exiting type.

huangapple
  • 本文由 发表于 2017年3月14日 02:52:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/42771289.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定