Can I Convert a String to an Enum Value in D? - enums

I have the following enum declared which using a string as its underlying value:
enum IssueType : string {
STUDENT_LEAVING = "leaving",
STUDENT_CONFLICT = "conflict",
NEEDS_ARCHIVE = "archive",
OTHER = "other"
}
I want to be able to do the following:
string s = "conflict";
IssueType type = std.conv.to!IssueType(s);
Currently, it is only possible to convert from a string to the enum by providing a case-sensitive match for one of the enum value names, like in this case the string "STUDENT_CONFLICT" would be accepted, while I want "conflict" to be accepted.

Simply cast the string to the enum type.
IssueType type = cast(IssueType)s;

Related

Does type definition help assign restricted values?

In the below struct type:
type Employee struct {
Name string `json:"name"`
JobTitle JobTitleType `json:"jobtitle"`
}
member JobTitle should be ensured to have restricted(specific) values( of string type).
type JobTitleType string
const(
GradeATitle JobTitleType = "Clerk"
GradeBTitle JobTitleType = "Manager"
)
Does type definition(JobTitleType) help assign restricted values to member JobTitle?
No. You can assign any value to JobTitle:
e.JobTitle=JobTitleType("bogus")
The JobTitleType is based on string, so all string values can be converted to it.
You can use getter/setters to enforce runtime validation.
No, it will not restrict the values, any value that has type JobTitleType can be assigned to JobTitle. Currently, there is no enum type in Go. For restricting values you will probably need to write your own logic.
No, you should use it in the validation logic. For example, https://github.com/go-playground/validator has oneOf operator for validation.
Go don't have enum type, but you can do something like this
package main
import (
"fmt"
)
var JobTitleTypes = newJobTitleTypeRegistry()
func newJobTitleTypeRegistry() *jobTitleTypeRegistry{
return &jobTitleTypeRegistry{
GradeATitle : "Clerk",
GradeBTitle : "Manager",
}
}
type jobTitleTypeRegistrystruct {
GradeATitle string
GradeBTitle string
}
func main() {
fmt.Println(JobTitleTypes.GradeATitle)
}

How can I choose which struct member to update at runtime?

Say I have a struct in Go that looks like this:
LastUpdate struct {
Name string `yaml:"name"`
Address string `yaml:"address"`
Phone string `yaml:"phone"`
}
Now say I want to create a function that accepts the name of the field (eg. "Phone") and then updates that field to a value, like today's date.
How can I build the function in a way that it will accept the name of the field and update that field in the struct?
I know that I could do an IF clause for each scenario (if field == "Phone") {var.LastUpdate.Phone = time.Now().Date()}, but I'd like to build this function so that I don't have to go add an IF clause every time I add a new member to this struct in the future. Thoughts?
Use the reflect package to set a field by name.
// setFieldByName sets field with given name to specified value.
// The structPtr argument must be a pointer to a struct. The
// value argument must be assignable to the field.
func setFieldByName(structPtr interface{}, name string, value interface{}) error {
v := reflect.ValueOf(structPtr)
v = v.Elem() // deference pointer
v = v.FieldByName(name) // get field with specified name
if !v.IsValid() {
return errors.New("field not found")
}
v.Set(reflect.ValueOf(value))
return nil
}
Use it like this:
var lu LastUpdate
setFieldByName(&lu, "Name", "Russ Cox")
Run it on the Playground

How to cast lambda parameters in Optional

I have a lambda expression like below. What I want to ask is Is there any easy way or best practice for the casting the lambda parameter(x) to String?
Optional.ofNullable(result).isPresent( x-> {
String value = (String) x;
});
When I try to change input type like
String value = (String) x;
I am getting below error;
Inconvertible types; cannot cast the lambda parameter to java.lang.String
You could do a safe casting:
Optional.of(result)
.filter(String.class::isInstance) // verify that Object is a String
.map(String.class::cast) // safely cast to String
.ifPresent( input-> {
// now input is a String
});

Golang Decode a BSON with special character Keys to a struct

I have a Golang struct called Person where all the properties have to be exported:
type Person struct {
Id string
Name string
}
Now I need to encode my MongoDB BSON response to this Person struct. The BSON looks like:
{
"_id": "ajshJSH78N",
"Name": "Athavan Kanapuli"
}
The Golang code to encode the BSON is:
mongoRecord := Person{}
c := response.session.DB("mydb").C("users")
err := c.Find(bson.M{"username": Credentials.Username, "password": Credentials.Password}).One(&mongoRecord)
The Problem:
_id is not getting encoded into Id
If I change the Person property into _Id, then it won't be exported.
How can I solve this problem?
Define your struct with json tag-
type Person struct {
Id string `json:"_id"`
Name string // this field match with json, so mapping not need
}
I tried to put a json tag like ,
type Person struct {
Id string `json:"_id"`
Name string // this field match with json, so mapping not need
}
But still it didn't work. Because the Mongodb returns '_id' which is of type bson.ObjectId . Hence changing the Struct tag to bson:"_id" and the type of the Person struct has been changed from string to bson.ObjectId. The changes done are as follows ,
type Person struct {
Id bson.ObjectId `bson:"_id"`
Name string
UserName string
IsAdmin bool
IsApprover bool
}
And It works!

How to convert ODataEnumValue into its CLR enum type?

While traversing the expression tree from a FilterQueryOption, I have an instance of a ODataEnumValue. I'm wondering how to convert that into the corresponding CLR enum type value in generic way (i.e. without having to look-up the actual CLR type myself).
Maybe you can refer to ODataEnumDeserializer's ReadInline method, which convert ODataEnumvalue to CLR enum type if it is in EdmModel.
The enum type can be retrieved by getting the ClrTypeAnnotation of the TypeReference as follows. First get the model from the FilterQueryOption instance:
IEdmModel _model = filterQueryOption.Context.Model;
Then, later when parsing its FilterClause, for example for a ConstantNode:
private object GetClrValue(ConstantNode constantNode)
{
ODataEnumValue enumValue;
...
else if ((enumValue = constantNode.Value as ODataEnumValue) != null)
{
var annotation = _model.GetAnnotationValue<ClrTypeAnnotation>(constantNode.TypeReference.Definition);
Type enumType = annotation.ClrType;
parameterValue = Enum.Parse(enumType, enumValue.Value);
}
...
}

Resources