How to pass an enum value to a function? [closed] - enums

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 2 years ago.
Improve this question
I have several enums:
enum Foo {
A(A),
B(B)
}
enum A {
C(i32),
D(i32)
}
enum B {
E(i32),
F(i32)
}
How could I write a function that takes a Foo and checks if it is, say, a B::E, then returns an Option<Foo>?
Edit: for clarification, the enum value is passed as an argument. I tried doing it with a signature of f(value: Foo, expected: Foo) but I'm not sure how to call that, as (with B::E again) the compiler wants an i32 supplied.

You can't do it with a function, because function parameters must be complete values and the way you would express "variant E of enumeration B" is with a pattern. But you can do it with a macro, which can take patterns as arguments.
First here is how you would do it with a fixed pattern in a function:
fn filter_e (x: Foo) -> Option<Foo> {
match x {
Foo::B (B::E (_)) => Some (x),
_ => None,
}
}
Now if we want to make the pattern into a parameter, we need to wrap this code in a macro:
macro_rules! filter_foo {
($x:expr, $p:pat) => {{
let x = $x;
match x {
$p => Some (x),
_ => None,
}
}}
}
Which you then call like this:
filter_foo!(x, Foo::B (B::E (_)))
For more details on macros, see The Little Book of Rust Macros.

I'm not sure if this answers the problem you're having, but you can use a match expression:
fn my_function(f: Foo) -> Option<Foo> {
match f {
Foo::B(B::E(_)) => { /* your code */ }
_ => None // otherwise, return None
}
}

Related

can you use a primitive or inbuild data types as a method in golang [closed]

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 1 year ago.
Improve this question
i wanna know if we are able to use inbuild data types as a method for a func in golang, cause whenever I use it as such, it shows an error
You can define methods on built-in types by first wrapping them with your own types, like this:
type MyInteger int
func (my MyInteger) Tell() {
fmt.Println("I'm MyInteger with value", my)
}
func main() {
var my MyInteger = 42
my.Tell()
}
You can try this on the Go Playground, it will print:
I'm MyInteger with value 42
This can be useful if you want to make a built-in type implement an interface. For example, here's how MyInteger would implement the fmt.Stringer interface:
type MyInteger int
func (my MyInteger) String() string {
return "MyInteger " + strconv.Itoa(int(my))
}
func main() {
var my MyInteger = 42
fmt.Println(my)
}

Multiple receivers on a single method [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Is it possible to have multiple receivers on a single function? In other words, a single function can belong to two or more structs?
Say I have
type Struct1 struct {
foo.Client
}
func CreateClient() struct1 {
return struct1{
ClientID: cId,
// ...
}
}
func (s *Struct1) MyFunc( // ... ) {}
But I also want to be able to associate MyFunc with another struct (different package):
type Struct2 struct {
lgr log.logger
}
func NewStruct2 (l *log.logger) (*Struct2, err) {
return &Struct2{mylog: *l}, nil
}
So what I want to actually have is:
func (s1 *Struct1, s2 *Struct2) MyFunc( // ... ) {}
"Is it possible to have multiple receivers on a single function?" -- It is not possible.
https://golang.org/ref/spec#Method_declarations
The receiver is specified via an extra parameter section preceding the
method name. That parameter section must declare a single non-variadic
parameter, the receiver.

What is better in Rust: defining a static variable to access it globally or passing a non-static variable through function arguments? [closed]

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
If a variable is used in multiple functions in a file, is it better to define it as static rather than passing a non-static variable through function arguments? Does this have a performance impact?
An example using a static variable:
lazy_static! {
static ref FOO: Foo = {
Foo::new()
};
}
fn main() {
do_foo();
do_another_foo();
}
fn do_foo() {
FOO.bar();
// ...
}
fn do_another_foo() {
let name = FOO.name();
// ...
}
An example using a normal variable:
fn main() {
let foo = Foo::new();
do_foo(&foo);
do_another_foo(&foo);
}
fn do_foo(foo: &Foo) {
foo.bar();
// ...
}
fn do_another_foo(foo: &Foo) {
let name = foo.name();
// ...
}
If you are using lazy_static!, there is quite a bit of overhead every time the variable is accessed. As the name suggests, lazy_static! vars are initialized lazily (on demand). That means every time one attempts to read the static variable, there is a check to make sure the variable is initialized or initialize it accordingly.
lazy_static! would probably be a lot slower than passing the variable through function argument.
There are also the const and static keywords.
In the case of the const keyword, the value is inlined where the const is used (think #define in C++).
In the case of the static keyword, there is only 1 instance of the variable that is inlined in the binary. Referencing the static variable would be like a pointer to part of the binary.
Both of these options would be faster than using lazy_static! when possible.
Also, with compiler optimizations, functions are likely to be inlined. The compiler can then optimize away the argument passing. Then there wouldn't be any overhead for passing arguments at all.
I would guess that function arguments are about on par with const/static.
That said, generally prefer passing state through function arguments rather than using global state. Global state tends to lead towards messy code and thus poor performance.

What is difference between these functions? [closed]

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 2 years ago.
Improve this question
What difference between the following functions?
func DoSomething(a *A){
b = a
}
func DoSomething(a A){
b = &a
}
First function receives pointer to value of type A. Second receives copy of value of type A. Here's how you call first function:
a := A{...}
DoSomething(&a)
In this case DoSomething receives pointer to original object and can modify it.
And here's call for second function:
a := A{...}
DoSomething(a)
In this case DoSomething receives copy of a, so it can't modify original object(but if original object contains pointers to other structs it can modify them)
func DoSomething(a *A) { // a is a pointer to given argument of type A
b = a // b is a copy of a, which is also the same pointer
// this is useful to change the given object directly
}
func DoSomething(a A) { // a is a copy of the given object type A
b = &a // b is the pointer of a
}
Remember, a pointer is a variable which holds a memory address.

Is it possible to combine variadic args with flag package usage? [closed]

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 4 years ago.
Improve this question
I want my function to take optional arguments in an efficent way.
Reading similar posts led me to variadic args and I'm trying to implement it alongside the flag package (simply looking for any alternative to the users being able to run available command line flags of their choice..
This is my flag package usage:
func main() {
var target string
var method string
flag.StringVar(&target, "target", "http://google.com/robots.txt", "Target address")
flag.StringVar(&method, "method", "GET", "Method")
flag.Parse()
requests.MakeRequest(target, method)
}
This is an example of variadic args function:
func foo(params ...int) {
fmt.Println(len(params))
}
func main() {
foo()
foo(1)
foo(1, 2, 3)
}
Can I combine the two?
If this is not possible - how can I pass main program's user given arguments to a variadic function then?
Your question shows a misunderstanding, what variadic arguments are for.
As you realized, variadics are used, when the amount of arguments to a function varies. You try to use this concept to hand over parsed commandline arguments of a variable amount. This is a bad idea in many ways. The obvious here is, that you are coupling your commandline arguments with the distribution of the flags and arguments in your code. Another is, that the variadic arguments loose the positional information. How do you expect to identify which 4 of the 5 arguments you have received?
You should define a struct to hold the flags for your code and write a commandline parser, that fills or creates this struct from defaults and given commandline options.
This struct is then used to provide the flags and options throughout your application.
In practice, this could look like this:
type options struct {
target string
method string
}
func main() {
config := parseCommandLine()
theRealStuffHappensHere(config)
}
func theRealStuffHappensHere(config options) {
if config.method == "GET" {
// ...
}
}
func parseCommandLine() options {
var config options
flag.StringVar(&(config.target), "target", "http://google.com/robotstxt", "Target address")
flag.StringVar(&(config.method), "method", "GET", "Method")
flag.Parse()
return config
}
The variadic arguments are heavily used in the fmt package, where the amount of required arguments depends on the amount of placeholders in the format string. Your usecase does not match.

Resources