douyo770657
2016-06-17 14:39
浏览 1.5k
已采纳

在golang中连接多个切片

I'm trying to merge multiple slices as follows,

package routes

import (
    "net/http"
)

type Route struct {
    Name        string
    Method      string
    Pattern     string
    Secured     bool
    HandlerFunc http.HandlerFunc
}

type Routes []Route

var ApplicationRoutes Routes

func init() {
    ApplicationRoutes = append(
        WifiUserRoutes,
        WifiUsageRoutes,
        WifiLocationRoutes,
        DashboardUserRoutes,
        DashoardAppRoutes,
        RadiusRoutes,
        AuthenticationRoutes...
    )
}

However the builtin append() is capable of appending two slices, hence it throws too many arguments to append at compile time. Is there an alternative function to achieve the task? or is there a better way to merge the slices?

图片转代码服务由CSDN问答提供 功能建议

我正尝试如下合并多个切片,

 包路由
 
导入(
“ net / http” 
)
 
type路由结构{
名称字符串
方法字符串
模式字符串
安全布尔
 HandlerFunc http.HandlerFunc 
}  
 
类型路由[]路由
 
var ApplicationRoutes路由
 
func init(){
 ApplicationRoutes = append(
 WifiUserRoutes,
 WifiUsageRoutes,
 WifiLocationRoutes,
 DashboardUserRoutes,
 DashoardAppRoutes,
  RadiusRoutes,
 AuthenticationRoutes ... 
)
} 
   
 
 

但是内置的append()可以附加两个切片,因此抛出 在编译时要附加的参数过多。 是否有替代功能来完成任务? 还是有更好的方式合并切片?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dongyuan9292 2016-06-17 14:46
    最佳回答

    append operates on individual elements, not on entire slices. Append each slice in a loop

    routes := []Routes{
        WifiUserRoutes,
        WifiUsageRoutes,
        WifiLocationRoutes,
        DashboardUserRoutes,
        DashoardAppRoutes,
        RadiusRoutes,
        AuthenticationRoutes,
    }
    
    var ApplicationRoutes []Route
    for _, r := range routes {
        ApplicationRoutes = append(ApplicationRoutes, r...)
    }
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题