英文:
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 "" 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 "" (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 := "Medium Level Alarm"
	message2 := "High Level Alarm"
	message3 := "Normal Operation"
	message4 := ""	//**empty string**
	
	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 //**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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论