How to set default values in Go structs

One possible idea is to write separate constructor function //Something is the structure we work with type Something struct { Text string DefaultText string } // NewSomething create new instance of Something func NewSomething(text string) Something { something := Something{} something.Text = text something.DefaultText = “default text” return something }

Named tuple and default values for optional keyword arguments

Python 3.7 Use the defaults parameter. >>> from collections import namedtuple >>> fields = (‘val’, ‘left’, ‘right’) >>> Node = namedtuple(‘Node’, fields, defaults=(None,) * len(fields)) >>> Node() Node(val=None, left=None, right=None) Or better yet, use the new dataclasses library, which is much nicer than namedtuple. >>> from dataclasses import dataclass >>> from typing import Any >>> … Read more

C# 4.0: Can I use a TimeSpan as an optional parameter with a default value?

You can work around this very easily by changing your signature. void Foo(TimeSpan? span = null) { if (span == null) { span = TimeSpan.FromSeconds(2); } … } I should elaborate – the reason those expressions in your example are not compile-time constants is because at compile time, the compiler can’t simply execute TimeSpan.FromSeconds(2.0) and … Read more

How to set a default entity property value with Hibernate

If you want a real database default value, use columnDefinition: @Column(name = “myColumn”, nullable = false, columnDefinition = “int default 100”) Notice that the string in columnDefinition is database dependent. Also if you choose this option, you have to use dynamic-insert, so Hibernate doesn’t include columns with null values on insert. Otherwise talking about default … Read more

Invoking methods with optional parameters through reflection

According to MSDN, to use the default parameter you should pass Type.Missing. If your constructor has three optional arguments then instead of passing an empty object array you’d pass a three element object array where each element’s value is Type.Missing, e.g. type.GetParameterlessConstructor() .Invoke(BindingFlags.OptionalParamBinding | BindingFlags.InvokeMethod | BindingFlags.CreateInstance, null, new object[] { Type.Missing, Type.Missing, Type.Missing }, … Read more