去子串操作,没有索引越界?

标签 go

我想知道为什么第二个 fmt.Println 中的“s[1:]”没有抛出索引超出范围错误?索引 1 明显超出范围

package main

import "fmt"

func main() {

   s := "J"

   //fmt.Println(s[1]) // This results in a runtime error: index out of range

   fmt.Println(s[1:]) // Why does this work? Index value 1 is clearly out of range, but the statement prints an empty string

}

最佳答案

作为language specification状态,给定 slice 表达式

a[low : high]

For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range. [...] If the indices are out of range at run time, a run-time panic occurs.

在你的例子中

s[1:]

low1 , highlen(s)len(s)1 .自 low <= len(s) ,没有 panic 。

关于去子串操作,没有索引越界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36439191/

相关文章:

mysql - 使用golang在mysql中创建数据库

go - := mean in Go? 是什么

multithreading - 如何在go中转换以下Thread语句

go - 如何将值附加到 ...interface{}?

戈朗 : why following code snippet do not write to file?

go - 如何使用 go gin 从 Auth0 jwt token 检索权限

go - 如何在 yocto 配方中管理 golang 项目的外部依赖

go - 如何在不使用time.Sleep的情况下等待所有goroutine完成?

go - 当我将 go mod 添加到我的项目时,无法运行它,我该如何解决?

go - 牛顿法有更优雅的 Go 实现吗?