检测变量的状态变化

huangapple go评论104阅读模式
英文:

Detecting State Change for a variable

问题

我正在编写一段代码,根据阈值检测状态变化。主要目标是只在状态变化时从函数中获取返回值。以下是我目前编写的代码。如果变量的状态没有改变,我们目前会在函数的返回值中返回一个空字符串""。有没有办法在状态不变时抑制返回值,而不是返回一个空字符串?

func (f *stateChange) Exec(args []interface{}, _ api.FunctionContext) (interface{}, bool) {
    
    m1 := args[0]
    m2 := m1.([]interface{})
    valarray := []float64{}
    
    for _, v := range m2 {
        valarray = append(valarray, v.(float64))
    }
    
    
    firstval := valarray[0]
    secondval := valarray[1]
    
    message1 := "Medium Level Alarm"
    message2 := "High Level Alarm"
    message3 := "Normal Operation"

    message4 := "" //**空字符串**
    
    if secondval >= 50 && secondval < 100 && firstval < 50{
    
    return message1, true
    }
    if firstval >= 100 && secondval < 100 && secondval >= 50{
    
    return message1, true
    }    
    
    if secondval >= 100 && firstval < 100{
    
    return message2, true    
    }    
    
    if firstval >= 50 && secondval < 50 {
    
    return message3, true
    
    }
    
    return message4, true //**需要抑制此输出中的空字符串**
    

}
英文:

I am writing a code to detect state change based on a threshold value. Main goal is to get a return value from the function only when the state changes. Here is the code I have written so far. If the state of variable does not change currently we are returning &quot;&quot; empty string in the return value of the function. Is there a way that we can suppress the return value if the state does not changes, instead of returning &quot;&quot; (empty string)

`

func (f *stateChange) Exec(args []interface{}, _ api.FunctionContext) (interface{}, bool) {
	
	m1 := args[0]
	m2 := m1.([]interface{})
	valarray := []float64{}
	
	for _, v := range m2 {
	    valarray = append(valarray, v.(float64))
	}
	
	
	firstval := valarray[0]
	secondval := valarray[1]
	
	message1 := &quot;Medium Level Alarm&quot;
	message2 := &quot;High Level Alarm&quot;
	message3 := &quot;Normal Operation&quot;

	message4 := &quot;&quot;	//**empty string**
	
	if secondval &gt;= 50 &amp;&amp; secondval &lt; 100 &amp;&amp; firstval &lt; 50{
	
	return message1, true
	}
	if firstval &gt;= 100 &amp;&amp; secondval &lt; 100 &amp;&amp; secondval &gt;= 50{
	
	return message1, true
	}	
	
	if secondval &gt;= 100 &amp;&amp; firstval &lt; 100{
	
	return message2, true	
	}	

	if firstval &gt;= 50 &amp;&amp; secondval &lt; 50 {
	
	return message3, true
	
	}
	
	return message4, true //**empty string in return need to suppress this output**
	

}

`

答案1

得分: 1

抑制此输出的最佳方法是使用 nil

return nil, true
英文:

The best way to suppress this output is using nil.

return nil, true

huangapple
  • 本文由 发表于 2021年7月2日 05:46:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/68217293.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定