我遇到了一些应该很简单的问题。我正在研究使用codegangsta优秀的cli
包的东西,但我试图从嵌套结构中访问属性并失败。
举个例子,我有:
func Something() []cli.Flag {
return []cli.Flag{
cli.StringFlag{
Name: awesome
Usage: "be awesome"
},
cli.StringFlag{
Name: awesome2
},
<etc.>
}
我有一个函数接收返回的flags []cli.Flag
并尝试为每个成员打印出Name
的字符串值,但我似乎无法访问切片中的嵌套内容。这样做的正确方法是什么?
编辑:这是我做的,加上Mayank的优秀答案
func PrintFlagsForDriver(name string) error {
for driverName := range drivers {
if name == driverName {
driver := drivers[driverName]
flags := driver.GetCreateFlags()
stringFlag, ok := flags[0].(cli.StringFlag)
if ok {
fmt.Println(stringFlag.Name)
}
}
}
return fmt.Errorf("Driver %s not found", name)
}
我现在遇到index out of range
运行时错误,但我认为这是我做错的其他事情。
答案 0 :(得分:3)
我假设您正在访问类似这样的值
./main.go:10: a[0].Name undefined (type cli.Flag has no field or method Name)
哪会出现以下错误
package main
import "fmt"
import "github.com/codegangsta/cli"
func main() {
a := Something()
stringFlag, ok := a[0].(cli.StringFlag)
if ok {
fmt.Println(stringFlag.Name)
}
}
func Something() []cli.Flag {
return []cli.Flag{
cli.StringFlag{
Name: "awesome",
Usage: "be awesome",
},
cli.StringFlag{
Name: "awesome2",
},
}
}
此代码的问题在于您通过接口cli.Flag访问struct cli.StringFlag值。您需要键入将此接口转换为实际的结构类型。
希望以下代码可以使事情变得清晰。
012-345-6
答案 1 :(得分:0)
因为您没有粘贴读取<style>
#map-canvas {
height: 350px;
width: 600px;
}
</style>
<script src="http://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
<script src="../jquery/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
var map;
var polyLine;
var polyOptions;
var iconSize = 2;
function initialize() {
var mapOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(0,0)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addPoint(event);
});
}
function addPoint(event) {
var pathHouse = 'M 0,1 , 0,-1 , -7,-1 , -7,-16 , -10,-16 , 0,-26 , 10,-16 , 7,-16 , 7,-1 , 0,-1 , 0,-4 , -3,-4 , -4,-5 ,-3,-4 , 3,-4 , 4,-5 , 4,-9 , 3,-10 , -3,-10 , -4,-11 , -4,-15 , -3,-16 , 3,-16 , 4,-15 , 4,-15 , 3,-16 , -3,-16 , -4,-15 , -4,-11 , -3,-10 , 3,-10 , 4,-9 , 4,-5 , 3,-4 , -3,-4 , -4,-5 , -3,-4 , 0,-4 , z';
var icon = {
path: pathHouse ,
fillColor: '#FF0000',
fillOpacity: .6,
anchor: new google.maps.Point(0,0),
strokeWeight: 0,
scale: iconSize,
strokeColor: 'black',
strokeWeight: 1
}
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable: false,
icon: icon,
zIndex : -20
});
map.panTo(event.latLng);
iconSize += .05;
}
$(document).ready(function() {
initialize();
});
</script>
<p>Click to add markers</p>
<div id="map-canvas"></div>
属性的代码,我猜,您需要进行界面检查
Name