英文:
Function not returning variable in dart
问题
我在Dart中创建了一个函数,旨在更改一个变量并返回以供以后在程序中使用。它没有像预期的那样更改变量。以下是我的代码:
String example = "not working :/";
String make(){
String example = "Hello World";
return example;
}
void main() {
make();
print(example);
}
我希望它打印出"Hello World",但实际上我仍然得到原始的"not working :/"。
我尽力使函数更改变量,但没有成功。
任何帮助将不胜感激。
英文:
I made a function in dart that is meant to change a variable and return it for use later in the program. It doesn't change the variable like it is supposed to. Here is my code:
String example = "not working :/";
String make(){
String example = "Hello World";
return example;
}
void main() {
make();
print(example);
}
I want it to print out hello world but instead I still get the original "not working :/"
I tried everything I could to make the function change the variable with no luck.
Any help appreciated.
答案1
得分: 0
在函数 make()
中,您声明了一个名为 example
的局部变量,声明如下:String example = "Hello World"
。这会重新声明 example
,从而隐藏了全局的 example
。
有一些可以采取的方法。
1. 赋值给全局变量
String example = "not working :/";
void make() {
example = "Hello World";
}
void main() {
make();
print(example);
}
输出结果:
Hello World
请注意,这里只有一个赋值操作,没有声明。example = ...
是一个赋值操作;String example = ...
是一个声明操作。
这是一个具有全局副作用的函数的示例。
2. 返回一个值
String example = "not working :/";
String make() {
return "Hello World"
}
void main() {
example = make();
print(example);
}
输出结果:
Hello World
一般来说,方法 #2 应该优先考虑,因为它没有副作用,除非有特殊原因选择其他方法。
可能有一些用例,其中结合方法 #1 和方法 #2(即同时赋值给全局变量并返回值,就像您在示例代码中尝试做的那样)是有意义的。但我建议除非有特定原因,否则限制自己只使用其中一种方法。
英文:
In the function make()
you are declaring a local named example
with the declaration String example = "Hello World"
. This re-declared example
shadows the global example
.
There are a couple things you could do.
1. Assign the global
String example = "not working :/";
void make() {
example = "Hello World";
}
void main() {
make();
print(example);
}
Output:
Hello World
Note the assignment of example
, without a declaration. example = ...
is an assignment; String example = ...
is a declaration.
This is an example of a function with a global side effect.
2. Return a value
String example = "not working :/";
String make() {
return "Hello World";
}
void main() {
example = make();
print(example);
}
Output:
Hello World
Generally speaking, approach #2 should be preferred due to the lack of side effect, unless there is a compelling reason to do otherwise.
It's possible there are some use cases in which it would make sense to combine approaches #1 and #2 (i.e. both assign a global as well as return the value, as it appears you're attempting to do in your example code). But I suggest limiting yourself to one or the other unless there's a specific reason to do otherwise.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论