Home > Backend Development > Golang > Pass parameters based on conditions

Pass parameters based on conditions

WBOY
Release: 2024-02-09 10:15:08
forward
1247 people have browsed it

Pass parameters based on conditions

In PHP, passing parameters based on conditions is a common programming technique, which allows us to flexibly pass parameters to functions or methods according to different situations. By passing parameters conditionally, we can dynamically change the behavior or results of the function according to different needs. This technique is very useful in actual development and can improve code reusability and flexibility. Next, PHP editor Xiaoxin will introduce in detail how to pass parameters according to conditions in PHP.

Question content

I have a function that accepts variable parameters.

func MyFunc(strs ...string)
MyFunc(entry1, entry2, entry3)
Copy after login

My use case is to pass one of the entries based on some conditions.

Is it possible to have a similar effect like below (so that I don't need to call MyFunc 's if-else in both):

MyFunc(entry1, if(condition)entry2, entry3)
Copy after login

Solution

Just prepare the parameters as slices:

myArgs := []string{"entry1"}
if (condition) {
    myArgs = append(myArgs, "entry2")
}
myArgs = append(myArgs, "entry3")
Copy after login

Then call the variadic function with your slice:

MyFunc(myArgs...)
Copy after login

The above is the detailed content of Pass parameters based on conditions. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template