3 ms·
"Now when you need to read from a file, you just do: ReadFile(filename, func(file) { fmt.println(file.Read()) }); Now you’re safely guaranteed
by jimbokun 16y ago
"Now when you need to read from a file, you just do:
ReadFile(filename, func(file) {
fmt.println(file.Read())
});
Now you’re safely guaranteed to close the file when the operation is done. This works because Go has lexical closures, a really nice feature. But the syntax for this is ungainly. Ruby addresses this with block arguments. Translated to Go, they could look something like:
ReadFile(filename) do(file) {
fmt.println(file.Read())
}
"
He does realize, that all he did was replace "func" with "do", and moved some parentheses around, right?
Are there other examples where the difference is more dramatic than this?
- barrkel 16y agoOf course he does. And yes, this small syntactic difference does have effects in the real world; rename 'func' to 'delegate', and with the addition of a semicolon (at the end of the println() call) this is valid C# code today - but almost noone writes their resource protection using this idiom because it's ugly.
- masklinn 16y ago> this is valid C# code today - but almost noone writes their resource protection using this idiom because it's ugly. Incorrect (and you don't need delegate, C# has lambdas now). It's because C# doesn't use that for its stdlib and instead has a (redundant) special form and defined protocols.
- barrkel 16y agoIt is correct to say that replacing the func with delegate and adding the semicolon makes it valid C# syntax. The correctness of that statement is completely independent of C# lambdas, which are neither a complete subset nor a complete superset of C# anonymous delegates. And it is ugly. It's ugly because the argument list visually expands across more than one line, including whole statements. The "redundant" forms of "using" and "lock" are both more limited than the closure-passing approach, but their limitations haven't been pressing enough to overcome much of tthe ugliness of the closure-as-parameter approach for this specific case of passing a statement block.