Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
A lambda function can be inlined in the source code. They are useful to pass these procedures as parameters to other modules. However, this can also be achieved through function pointers. Is there any set of good practices or rules of thumb regarding When should I choose lambdas over function pointers in C++11?
A lambda expression can capture variables, creating a closure type that has data associated with it. You can't bind data to a function pointer, the function can only operate on its parameters and global data.
Chose lambda expression over pointer to function.
I think you should not choose function pointers. Instead, in C++11 you have function objects and lambdas, a lambda being considered an anonymous local function object (though no two lambda expressions are equal; they don't have return types; they are closure types).
I consider them a technical legacy from C that C++ supports. Unless you are working with C or legacy code you might as well consider not to pay too much attention to function pointers.
A pointer to function can be cast to a different pointer-to-function type.
A lambda has access to its scope's variables, which you can specify in the capture list.
A lambda can outlive its caller (pass lambda to different thread, or stored for later usage). And this can be a problem when local variables are captured inappropriately (i.e. by reference).
The argument list of a lambda can be omitted. I.e. the shortest lambda is []{}.
A lambda expression's return type can be deduced from its body.
When small and used only once: lambda
When not small or reused: function object
If your lambda expression is more than a few lines (three?) it could be good to make a function out of it.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
As in java8:
someList.stream().map(e->e.getXXX()).toList()
For example, I have a Student array/slice, and the struct Student contains properties like Id, Name, and so on.
I want to extract all Ids into a NEW array/slice with one-line code like java8 as mentioned above, instead of range. Is there is an example?
Currently there is not an easy, builtin way to do this. Although Go has first-class functions and lexical closure, it's not possible to write a function like map that will operate on arbitrary types in the way you want. (Also, there's no compact lambda syntax, but I consider that a relatively minor issue).
Instead, you have to do one of the following:
Operate on interface{}. While this would let you write a func map([]interface{}, func(interface{})interface{}) []interface{}, you lose compile-time type safety, you lose performance, and a []interface{} is not a []string (or whatever the type is of the field you wanted to fetch), nor can you even type-assert it to one, so working with the result is cumbersome.
Use code-generation. There are libraries out there that will generate map/filter/etc. code for you, specialized to given types, so that none of the disadvantages of #1 apply. And Go ships with a Go parser in the standard library, so most code generators are fairly robust. But code generation is a separate build step, hampers debuggability, and can hurt the clarity of code.
Just live with boilerplate, writing lots of loops, and forget about trying to achieve functional style.
Wait for Go 1.18 to bring generics, which should make libraries of functional idioms a lot more practical.
Most experienced Go users would recommend approach #3, and so do I (reluctantly).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
As far as I can tell, when passing a function as an input into another function it must have an identical contract - not allowing for the ability to leverage interfaces as follows: (runnable example here: https://play.golang.org/p/LXvNgziDdgp)
package main
func main() {
foo(processS1)
}
type I1 interface {
bar()
}
type S1 struct {
}
func (s1 S1) bar() {
}
func processS1(s S1) {
}
func foo(func(I1)) {
}
from a type-system perspective, the assumed issue is that a function type is passed, and not an interface. but, I can't see what the issue would be with allowing the type system to infer the relationship here. I believe I've seen this in other languages.
Any reason as to why Go can't/won't support this?
In short the relationship you've defined there is not valid in any typed language.
You've defined foo as a function that takes a type func(I1). func(S1) is a different type. The complexities of the relationships between these types is more complex than simple inheritance. The golang team has chosen simplicity over solving for function type and signature matching.
One way these complexities become apparent is you've actually defined the relationship backwards. Imagine there was an struct s2 that also implemented I1. Also, s1 had a method baz().
If foo passed in S2{} to the function parameter it would implement I1, but processS1 would call a function that doesn't exist on the passed in struct.
runnable: https://play.golang.org/p/EvwQpCXhqTb
Even if you swapped the types (https://play.golang.org/p/ItUx5pRJ6-g), which would be able to run without panics, it still wouldn't work in golang. As to why golang doesn't try to solve these problems, I'm not sure you'll get a satisfactory answer. The team responds to these kind of questions with general philosophical views such as:
The simplicity of method matching is a feature of the language.
I do think your question here does help justify that view though. It's a complex the problem is hard to reason about. It's easier to just not solve it than add additional complexity.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
In some Golang Tips said that: small object should pass by value and big object should pass by reference.
But how big object is small object?
If a struct has 10+ Fields. should it pass by value?
As you see from the discussion it is "hard" to understand when to use a pointer or a reference. If you are learning the Golang I suggest to use this approach to decide when to use pointer or reference:
I need to use a struct only for read purpose
In this case I suggest to use a pointer to a struct, that's for performance reason (copy a struct is a time consuming operation as you can tell, no matter if is a "big" struct or a small one).
I need to use a struct on multiple function each one write something on the struct but the various function should be no influence each other
In this case you should pass the struct as reference.
I need to use a struct on multiple function each one write something on the struct and the various function should be use the result of previous function
In this case you should pass the struct by pointer.
As you can see this approach avoids to think about the "dimension" of the struct and focus on the use of the struct, I think this is a better approach because is not always easy to define the dimension of a struct.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have object initializer in my code, that initializes every field of my object explicitly. But in my case, most of the parameters have sensible defaults and I want to use them.
In Python I usually use combination of keyword arguments or defaults and my __init__ method contains some validation logic so I can use zero configuration principle in object initialization. For example:
class Foo:
"""This class designed to show zero configuration
principle in action"""
def __init__(self, mandatory, optional=None, **kwargs):
self.__field1 = mandatory
self.__field2 = optional or make_default2()
if 'bar' in kwargs:
self.__field3 = kwargs['bar']
else:
self.__field3 = make_default3()
f = Foo('mondatory', bar=Bar())
There is no parameters with default values in Go nor keyword parameters or function overloads. Because of that - it is difficult to write flexible initialization code (I don't care much about performance in such code usually).
I want to find most idiomatic way to write such code in Go. Maybe some combination of runtime type reflection and maps will do the job, what do you think?
Because newly-allocated memory in Go is always zeroed, the idiomatic way is to make explicit use of this fact by:
designing your structs to have have sane zero values
using composite literals
Take a look at the following section of Effective Go:
http://golang.org/doc/effective_go.html#data
For extremely complex cases, a configuration struct (option 3 at http://joneisen.tumblr.com/post/53695478114/golang-and-default-values) is also sometimes used, with a NewConfigStruct() that initializes a configuration instance with defaults. The user generates a default instance, sets the fields they want, then passes it to the New function for the actual struct they are creating.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
What do you think fellow programmers about using short functions vs using inline code?
Example with function:
//Check if all keys from $keys exist in $array
function functionName(array $array, array $keys) {
return array_diff($keys, array_keys($array));
}
functionName($mas,$keys);
vs. using just the code:
array_diff($keys, array_keys($mas));
I think that in your example, it's superfluous. There's no need to create an extra function call and add bytes to the filesize without good reason.
Also, the inline array_diff($keys, array_keys($mas)); is a lot easier to debug for fellow programmers, than looking through your code to find out exactly what functionName() does and where it is located.
It depends on what functionName actually is.
If you're using customerDetailsAreValid throughout your code and you suddenly have to add validation of $array['email'], you're going to be grateful for the separation of intent and implementation.
If on the other hand you're wrapping array_diff in the function diffArray there isn't much point.
I think clarity is a prime concern when writing logic you hope will be around for any amount of time.
In general, I abhor inline functions. I think they are lazy, promote spaghetti code, and in general exude a complete lack of concern for style/readability/clarity on the part of the developer.
Filesize - I find this argument very arbitrary. The js files are transmitted once and then cahced. In many cases, you find descriptive names, etc, (hopefully comments) that all add to file size. If size is very important , use a file minimizer that makes a file as tiny as possible.
Looking for a function? How about trying to figure out exactly what is going on in a voluminous docReady. CTL-F usually invokes a find facility.
I will grant that there can be simple cases where an inline function detracts little from the readability of the code. However, the inline approach will never be MORE CLEAR than the alternate separation of reference and implementation.
my two cents