Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于结构化绑定 #7

Open
nobodxbodon opened this issue Mar 22, 2021 · 9 comments
Open

关于结构化绑定 #7

nobodxbodon opened this issue Mar 22, 2021 · 9 comments

Comments

@nobodxbodon
Copy link
Contributor

(表达式1, 表达式2...) = 表达式3

表达式1 和 2 除了单个变量或者组合之外还可以是哪种结构呢?

比如 (a+b, a-b) = {5, 1} 应该不支持吧?

@mikecovlee
Copy link
Member

表达式是可以很多样化的,只要是支持赋值的左值对象即可

@nobodxbodon
Copy link
Contributor Author

似乎文档里没说明哪些表达式“支持赋值”。
另外,右边表达式是否也要说明必须是数组?刚试过字符串好像不允许,虽然 “ts"[0] 允许,但这样的话:

var (a,b) = "ts"

就会报错:
Runtime Error: Only support structured binding with array while variable definition.

@mikecovlee
Copy link
Member

右边必须是数组,谢谢提醒,我会在文档里注明

@mikecovlee
Copy link
Member

@nobodxbodon
Copy link
Contributor Author

不好意思。“支持赋值的左值对象”有哪里说明吗?

@mikecovlee
Copy link
Member

已补充,谢谢

@nobodxbodon
Copy link
Contributor Author

没理解错的话,是指左侧的任何“标识符”是“能够被赋值的左值对象(非临时对象)”吗?比如:

(a, (b, c)) = {1, {2, 3}} 

是指 a、b、c 都是“能够被赋值的左值对象”,而不是 a、(b, c)?

另外,确认一下关于表达式的定义,(b, c) 是一个表达式,b 和 c 也都分别是表达式?但 3.1 里的定义是 “表达式由操作数和运算符组成”?

@mikecovlee
Copy link
Member

左边的格式和右边是相关的,比如 (a, (b, c)) = {1, 2, 3} 就是不合法的,因为右侧的值期待的是 {value, {value, value}}
也就是说,左边的每个括号对应着一层数组
至于左侧的要求,不一定是标识符,比如某个函数返回一个值,或者一个表达式比如namespace.value,在这里都是可行的

@nobodxbodon
Copy link
Contributor Author

某个函数返回一个值

这种情况可否举个例子?一时没明白。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants