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.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
In OCaml, there is a construct called univ_map.t, which allows you to map from 'a Type_equal.Id.t values to 'as. Here is an example.
Is there a construct that would allow me to do something similar in Rust? I know in OCaml they are implemented with open variants, which I don't believe Rust has.
I'm not familiar with OCaml, but looking at the docs:
Univ_map: Universal/heterogeneous maps [...] useful for storing values of arbitrary type in a single map [...] built on top of Univ.
Univ: An extensible universal variant type. Every type id corresponds to one branch of the variant type.
The closest thing that Rust has that sounds like Univ is the Any trait, which is designed to represent any type (with exceptions). However, there is no standard type for storing a collection of Anys that is accessed by its TypeId. From looking how popular crates handle this, its usually a bespoke wrapper around HashMap<TypeId, Box<dyn Any>> or similar. I hope I've understood correctly.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I am currently learning go after C++. I just get stuck every time while facing interface.
e.g:
s := []interface{}{"a", "b", "c"}
How string could be an interface?
I am not getting in what sense interface is introduced in go. There are many more doubts regarding interface.
Answer to the above question and especially providing some learning resources regarding interface would be great.
Thanks in advance :)
By definition, an interface is defined as a set of method signatures. So it is used to indicate which methods should be implemented by another type. If the interface doesn't specify any method signatures in the interface declaration body then any valid type can be of the type of that interface since there are no prerequisites of being that interface.
In your example, the slice contains a type of interface{} meaning any type can be a valid candidate as the slice input.
s := []interface{}{"a", 1, false}
https://tour.golang.org/methods/9 is a good place for exploring and learning go.
You can think of an interface as a container that holds a value and the type of that value.
When you define your own interfaces the compiler will ensure that the values you assign (store in the interface) have methods that match what you specified in your interface definition.
Empty interfaces, interface{}, have no methods and can therefore store any value since there are no expectations for the existence of any particular methods.
If you have not already, check the section on interfaces in A Tour of Go.
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 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 9 years ago.
Improve this question
Sometimes I see code like
class Thing
def self.add_em(a,b)
a+b
end
end
and sometimes I see
class Thing
def self.add_em(a,b)
#a=a
#b=b
#a+#b
end
end
When/Why should I use the # instance variables instead of just using the parameters as passed?
I believe that one reason is if you want to use those variables in any other method then instance variables will be available and local, parameter based variables will not. However I frequently see # variables being used even though the variables are not being used in any other method.
So I see the pattern of
#a=a
#b=b
at the start of method for all parameters passed in being used a lot but I'm not clear exactly why if they are just used on that method. Is it just a convention in case they are used in other methods?
As you correctly realized, it does not make sense to define instance variables unless they are used in another method. If instance variables are used but are not called in any other method, then that code is probably not written by a good programmer.
But note that sometimes, method definitions are not obvious at first look. For example, if there is
class Thing
attr_reader :a
end
then there actually is a method that uses #a.
I'd say that they did it because they had plans to reference the arguments as instance variables. If not they failed the YAGNI (you aint gonna need it principle). If they changed their minds half way through (which has been known to happen...), they they forgot to tidy up.