Optional arguments

Context should be used to pass optional parameters around, and also used as a sort of catch-all, like Python kwargs or JavaScript arguments. Using context as a substitute for behaviors can be very problematic because it could cause the shadowing of variables, like we saw in the example of context.WithValue.

Another big drawback of this approach is hiding what's happening and making the code more obscure. A much better approach when it comes to optional values is using a pointer to structure arguments – this allows you to avoid passing the structure at all with nil.

Let's say you had the following code:

// This function has two mandatory args and 4 optional ones
func SomeFunc(ctx context.Context, arg1, arg2 int,
opt1, opt2, opt3, opt4 string) {}

By using Optional, you would have something like this:

type Optional struct {
Opt1 string
Opt2 string
Opt3 string
Opt4 string
}

// This function has two mandatory args and 4 optional ones
func SomeFunc(ctx context.Context, arg1, arg2 int, o *Optional) {}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.78.136