package main
import "fmt"
func main() {
var s []int
s = append(s, 2, 3, 4)
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
游乐场:https://play.golang.org/p/tx8gmx5eR7B
输出:
len=3 cap=4 [2 3 4]
输出应为:
2
3
4
我希望它没有循环。
答案 0 :(得分:2)
如果您不想使用fmt.Println并且仅在切片上使用printf和range而无需计算len,则类似的事情将起作用。
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:fillViewport="true"
android:overScrollMode="always"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/color_white"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/activity_insight_recyclerview_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="@dimen/_20sdp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:listitem="@layout/raw_insight" />
更新:发布此文章时,我还没有阅读您的评论部分,没有peterSO的for循环答案也很不错。
答案 1 :(得分:1)
逐行在Go中逐行打印切片中没有括号的元素。
评论:我希望它没有循环
例如,
package main
import "fmt"
func printSlice(s []int) {
if len(s) == 0 {
return
}
fmt.Println(s[0])
printSlice(s[1:])
}
func main() {
var s []int
s = append(s, 2, 3, 4)
printSlice(s)
}
游乐场:https://play.golang.org/p/ISXdbjTrfSt
输出:
2
3
4
答案 2 :(得分:0)
使用值和括号创建字符串。
打印不包括括号的子字符串,然后显示。
或使用JimB在评论中建议的strings.Trim
。
temp := fmt.Sprintf("%v", s)
fmt.Printf("len=%d cap=%d \n%v\n", len(s), cap(s), strings.Join(strings.Split(temp[1:len(temp)-1], " "), "\n"))
输出:
len=3 cap=4
2
3
4