跳到正文
hello world

TypeScript、Java、PHP、Python、Go 中定义枚举-存档记忆

在不同编程语言中,枚举的实现方式略有不同。下面以 ModelType 为例,定义两个模型类型:

  • MOBILE:移动端轻量模型
  • SERVER:服务端模型

对应的字符串值分别为:

mobile
server

1. TypeScript

TypeScript 支持字符串枚举,可以直接为枚举成员指定字符串值。

export enum ModelType {
  MOBILE = "mobile",
  SERVER = "server",
}

使用方式:

const modelType: ModelType = ModelType.MOBILE;

console.log(modelType);

输出:

mobile

2. Java

Java 枚举成员本身默认是对象。如果需要为枚举绑定自定义字符串值,可以添加 value 字段、构造方法和 getValue() 方法。

public enum ModelType {

    MOBILE("mobile"),
    SERVER("server");

    private final String value;

    ModelType(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}

使用方式:

ModelType modelType = ModelType.MOBILE;

System.out.println(modelType);
System.out.println(modelType.getValue());

输出:

MOBILE
mobile

其中:

modelType.name()

返回枚举名称:

MOBILE

而:

modelType.getValue()

返回对应的字符串值:

mobile

3. PHP

PHP 从 8.1 版本开始支持原生枚举。

<?php

enum ModelType: string
{
    case MOBILE = 'mobile';
    case SERVER = 'server';
}

使用方式:

$modelType = ModelType::MOBILE;

echo $modelType->name;
echo $modelType->value;

输出:

MOBILE
mobile

根据字符串获取枚举:

$modelType = ModelType::from('mobile');

如果字符串可能不存在,可以使用 tryFrom()

$modelType = ModelType::tryFrom('unknown');

if ($modelType === null) {
    echo '不支持的模型类型';
}

4. Python

Python 可以使用标准库中的 Enum 定义枚举。

from enum import Enum


class ModelType(Enum):
    MOBILE = "mobile"
    SERVER = "server"

使用方式:

model_type = ModelType.MOBILE

print(model_type)
print(model_type.name)
print(model_type.value)

输出:

ModelType.MOBILE
MOBILE
mobile

根据字符串获取枚举:

model_type = ModelType("mobile")

print(model_type)

输出:

ModelType.MOBILE

5. Go

Go 没有传统意义上的原生枚举,通常使用“自定义类型 + 常量”实现类似枚举的效果。

package model

type ModelType string

const (
    ModelTypeMobile ModelType = "mobile"
    ModelTypeServer ModelType = "server"
)

使用方式:

package main

import (
    "fmt"
)

func main() {
    var modelType ModelType = ModelTypeMobile

    fmt.Println(modelType)
    fmt.Println(string(modelType))
}

输出:

mobile
mobile

为了防止传入不支持的字符串,可以添加校验方法:

func (m ModelType) IsValid() bool {
    switch m {
    case ModelTypeMobile, ModelTypeServer:
        return true
    default:
        return false
    }
}

使用方式:

modelType := ModelType("unknown")

if !modelType.IsValid() {
    fmt.Println("不支持的模型类型")
}

总结

不同语言中 ModelType 枚举的实现方式如下:

语言 实现方式 获取字符串值
TypeScript 字符串枚举 ModelType.MOBILE
Java 枚举加自定义字段 ModelType.MOBILE.getValue()
PHP 字符串枚举 ModelType::MOBILE->value
Python Enum ModelType.MOBILE.value
Go 自定义类型加常量 string(ModelTypeMobile)

虽然不同语言的语法不同,但最终目的都是相同的:使用有限、明确的常量表示模型类型,避免在业务代码中直接使用容易写错的字符串。

评论

填写昵称与邮箱即可评论,无需登录。

推荐阅读