GO函数参数中的通用类型数组

时间:2015-08-20 19:59:05

标签: go

我有这个功能:

cannot use MyDataType (type []*model.MyDataType) as type []*interface {} in argument to middleware.functionX

我希望集合参数允许任何类型的数组,这就是为什么我尝试使用 * interface {} 但我收到错误的原因像这样:

from lxml import etree
from io import StringIO

xml = '''
<gpx creator="udos" version="1.1" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3">
 <metadata>
  <time>2015-07-07T15:16:40Z</time>
 </metadata>
 <trk>
  <name>some name</name>
  <trkseg>
   <trkpt lat="46.3884140" lon="10.0286290">
    <ele>2261.8</ele>
    <time>2015-07-07T15:30:42Z</time>
   </trkpt>
   <trkpt lat="46.3884050" lon="10.0286240">
    <ele>2261.6</ele>
    <time>2015-07-07T15:30:43Z</time>
   </trkpt>
   <trkpt lat="46.3884000" lon="10.0286210">
    <ele>2262.0</ele>
    <time>2015-07-07T15:30:46Z</time>
   </trkpt>
   <trkpt lat="46.3884000" lon="10.0286210">
    <ele>2261.8</ele>
    <time>2015-07-07T15:30:47Z</time>
   </trkpt>
  </trkseg>
 </trk>
</gpx>
'''

# this is to simulate that above xml was read from a file
file = StringIO(unicode(xml))   # with python 3 use "file = StringIO(xml)"

# reading the xml from a file
tree = etree.parse(file)

ns = {'xmlns': 'http://www.topografix.com/GPX/1/1',
      'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
      'xmlns:gpxtpx': 'http://www.garmin.com/xmlschemas/TrackPointExtension/v1',
      'xmlns:gpxx': 'http://www.garmin.com/xmlschemas/GpxExtensions/v3'}

expr = 'trk/trkseg/trkpt/ele'

for element in tree.xpath(expr, namespaces=ns):
    print(element.text)

1 个答案:

答案 0 :(得分:5)

你不能这样做,但是你可以很容易地做到这一点:

func functionX(collection interface{}) error {
    ...
    response, err := json.MarshalIndent(collection, "", "  ")
    ...
}

playground