From 8adef848c499317dff9680d07f2b3db1d5136fad Mon Sep 17 00:00:00 2001 From: huangdawei Date: Mon, 26 Aug 2024 16:51:13 +0800 Subject: [PATCH] =?UTF-8?q?update=201.=20=E5=A2=9E=E5=8A=A0=E4=BA=86?= =?UTF-8?q?=E4=B8=80=E4=B8=AA=E6=9D=A1=E4=BB=B6=E5=88=A4=E6=96=AD=E8=BF=94?= =?UTF-8?q?=E5=9B=9E=E6=B3=9B=E5=9E=8B=E7=BB=93=E6=9E=9C=E7=9A=84=E5=87=BD?= =?UTF-8?q?=E6=95=B0=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- condition.go | 24 ++++++++++++++++++++++++ condition_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 condition.go create mode 100644 condition_test.go diff --git a/condition.go b/condition.go new file mode 100644 index 0000000..01197aa --- /dev/null +++ b/condition.go @@ -0,0 +1,24 @@ +// Copyright 2021 ecodeclub +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package ekit + +// IfThenElse 根据条件返回对应的泛型结果,请注意,结果值在传入时就会访问,请务必确认其合法性 +// 例:传 trueValue 时传入了一个指针对象并调用其方法,需要先判空 +func IfThenElse[T any](condition bool, trueValue, falseValue T) T { + if condition { + return trueValue + } + return falseValue +} diff --git a/condition_test.go b/condition_test.go new file mode 100644 index 0000000..e449f19 --- /dev/null +++ b/condition_test.go @@ -0,0 +1,26 @@ +// Copyright 2021 ecodeclub +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package ekit + +import ( + "github.com/stretchr/testify/assert" + "testing" +) + +func TestIfThenElse(t *testing.T) { + i := 7 + i = IfThenElse(false, i, 0) + assert.Equal(t, i, 0) +}